package org.commcare.heartbeat;

import java.util.LinkedList;

/**
 * Created by amstone326 on 2/12/18.
 */

public class UpdatePromptShowHistory {

    private LinkedList<Boolean> showHistory;
    // the number of logins to keep in show history
    private int numLoginsToTrack;

    public UpdatePromptShowHistory() {
        this.numLoginsToTrack = UpdateToPrompt.getReducedShowFrequency() - 1;
        this.showHistory = new LinkedList<>();
    }

    /**
     *
     * @param showFrequency - The frequency with which we currently want to show update prompts;
     *                 if showFrequency is N, then this means "show the prompt once every N logins"
     * @return - If the prompt to whom this show history belongs should be shown right now, based
     * on the given showFrequency
     */
    boolean shouldShowOnThisLogin(int showFrequency) {
        boolean shouldShow = true;

        int numChecked = 0;
        int index = showHistory.size() - 1;
        while (index >= 0 && numChecked < showFrequency-1) {
            if (showHistory.get(index)) {
                shouldShow = false;
                break;
            }
            numChecked++;
            index--;
        }

        updateHistoryWithLatest(shouldShow);
        return shouldShow;
    }

    private void updateHistoryWithLatest(boolean lastShowValue) {
        if (isFull()) {
            showHistory.poll();
        }
        showHistory.add(lastShowValue);
    }

    private boolean isFull() {
        return showHistory.size() == numLoginsToTrack;
    }

}

@@ -26,16 +26,417 @@
 tbeat;%0A%0A
+import org.javarosa.core.util.externalizable.DeserializationException;%0Aimport org.javarosa.core.util.externalizable.ExtUtil;%0Aimport org.javarosa.core.util.externalizable.ExtWrapList;%0Aimport org.javarosa.core.util.externalizable.Externalizable;%0Aimport org.javarosa.core.util.externalizable.PrototypeFactory;%0A%0Aimport java.io.DataInputStream;%0Aimport java.io.DataOutputStream;%0Aimport java.io.IOException;%0A
 import j
@@ -540,16 +540,42 @@
 History 
+implements Externalizable 
 %7B%0A%0A    p
@@ -1972,10 +1972,515 @@
 %0A    %7D%0A%0A
+    @Override%0A    public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException %7B%0A        numLoginsToTrack = ExtUtil.readInt(in);%0A        showHistory = (LinkedList%3CBoolean%3E)ExtUtil.read(in, new ExtWrapList(Boolean.class, LinkedList.class), pf);%0A    %7D%0A%0A    @Override%0A    public void writeExternal(DataOutputStream out) throws IOException %7B%0A        ExtUtil.writeNumeric(out, numLoginsToTrack);%0A        ExtUtil.write(out, new ExtWrapList(showHistory));%0A    %7D%0A
 %7D%0A

implement externalization for ShowHistory; needs testing