package com.github.gquintana.beepbeep.store;

import com.github.gquintana.beepbeep.pipeline.*;

import java.time.Instant;

public class ScriptStoreUpdater<ID> extends Transformer<ScriptEvent, ScriptEvent> {
    private final ScriptStore<ID> store;

    public ScriptStoreUpdater(ScriptStore<ID> store, Consumer<ScriptEvent> consumer) {
        super(consumer);
        this.store = store;
    }

    @Override
    protected ScriptEvent transform(ScriptEvent event) {
        String fullName = event.getScript().getFullName();
        if (event instanceof ScriptStartEvent) {
            ScriptInfo<ID> info = store.getByFullName(fullName);
            boolean create = info == null;
            if (create) {
                info = new ScriptInfo<>();
                info.setFullName(fullName);
                info.setSize(event.getScript().getSize());
            }
            info.setStartDate(Instant.now());
            info.setEndDate(null);
            info.setStatus(ScriptStatus.STARTED);
            info.setSize(event.getScript().getSize());
            info.setSha1(event.getScript().getSha1Hex());
            if (create) {
                info = store.create(info);
            } else {
                info = store.update(info);
            }
        } else if (event instanceof ScriptEndEvent) {
            ScriptEndEvent endEvent = (ScriptEndEvent) event;
            ScriptInfo<ID> info = store.getByFullName(fullName);
            if (info == null) {
                throw new ScriptStoreException("Script end not in store " + event.getScript());
            }
            info.setEndDate(Instant.now());
            if (endEvent.isSuccess()) {
                info.setStatus(ScriptStatus.SUCCEEDED);
            } else {
                info.setStatus(ScriptStatus.FAILED);
            }
            info = store.update(info);
        }
        return event;
    }
}

@@ -114,16 +114,64 @@
 Instant;
+%0Aimport java.util.HashMap;%0Aimport java.util.Map;
 %0A%0Apublic
@@ -288,16 +288,91 @@
 %3E store;
+%0A    private final Map%3CString, ScriptInfo%3CID%3E%3E infoCache = new HashMap%3C%3E();
 %0A%0A    pu
@@ -725,35 +725,23 @@
  info = 
-store.getByFullName
+getInfo
 (fullNam
@@ -1356,32 +1356,75 @@
 ;%0A            %7D%0A
+            infoCache.put(fullName, info);%0A
         %7D else i
@@ -1561,27 +1561,15 @@
 o = 
-store.getByFullName
+getInfo
 (ful
@@ -1997,30 +1997,329 @@
     
-%7D%0A        return event
+    infoCache.clear();%0A        %7D%0A        return event;%0A    %7D%0A%0A    private ScriptInfo%3CID%3E getInfo(String fullName) %7B%0A        ScriptInfo%3CID%3E info = infoCache.get(fullName);%0A        if (info == null) %7B%0A            info = store.getByFullName(fullName);%0A            infoCache.put(fullName, info);%0A        %7D%0A        return info
 ;%0A  

Add local scriptinfo cache in script updater