package com.elphel.imagej.mcp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class McpDialogSession {
	public static final int debugLevel = -1; // name in the same case in most other places. Compares if (debugLevel >-3)
    private final String id;
    private final String title;
    private final List<McpDialogField> fields;
    private final Map<String, String> valuesByLabel;
    private final Object submitLock = new Object();
    private Boolean submittedOk = null;

    public McpDialogSession(String title, List<McpDialogField> fields) {
        this.id = UUID.randomUUID().toString();
        this.title = title;
        this.fields = new ArrayList<McpDialogField>(fields);
        this.valuesByLabel = new HashMap<String, String>();
    }

    public String getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public List<McpDialogField> getFields() {
        return Collections.unmodifiableList(fields);
    }

    public void setValue(String label, String value) {
        if (label == null) {
            return;
        }
        valuesByLabel.put(label, value);
        if (debugLevel > -3) {
        	System.out.println("setValue("+label+","+value+")");
        }
    }

    public void submit(boolean ok) {
        synchronized (submitLock) {
            submittedOk = Boolean.valueOf(ok);
            submitLock.notifyAll();
            if (debugLevel > -3) {
            	System.out.println("submit("+ok+")");
            }
        }
    }

    public Boolean awaitSubmit(long timeoutMs) {
        synchronized (submitLock) {
            if (submittedOk != null) {
                return submittedOk;
            }
            long deadline = System.currentTimeMillis() + timeoutMs;
            while (submittedOk == null) {
                long remaining = deadline - System.currentTimeMillis();
                if (remaining <= 0) {
                    break;
                }
                try {
                    submitLock.wait(remaining);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
            return submittedOk;
        }
    }

    public String getValue(String label) {
        if (label == null) {
            return null;
        }
        return valuesByLabel.get(label);
    }
}
