package com.elphel.imagej.mcp;

import java.util.ArrayList;
import java.util.List;

public class FileSelectMcp {
	public static final String LABEL_SINGLE = "Selected path";
	public static final String LABEL_MULTI = "Selected paths";

	private static final long TIMEOUT_MS = 30000L;
	private static final long POLL_MS = 200L;

	private FileSelectMcp() {
	}

	public static String selectSingle(boolean directory, String title, String initialValue) {
		List<McpDialogField> fields = new ArrayList<McpDialogField>(1);
		fields.add(new McpDialogField(
				McpDialogField.Type.STRING,
				LABEL_SINGLE,
				directory ? "Enter directory path" : "Enter file path",
				null,
				null,
				null,
				initialValue));
		McpDialogSession session = new McpDialogSession(title == null ? "Select path" : title, fields);
		McpDialogRegistry.setCurrent(session);
		String value = waitForValue(session, LABEL_SINGLE);
		McpDialogRegistry.setCurrent(null);
		return normalizeValue(value);
	}

	public static String[] selectMultiple(boolean directory, String title, String initialValue) {
		List<McpDialogField> fields = new ArrayList<McpDialogField>(1);
		fields.add(new McpDialogField(
				McpDialogField.Type.STRING,
				LABEL_MULTI,
				directory ? "Enter directory paths (comma or newline separated)" : "Enter file paths (comma or newline separated)",
				null,
				null,
				null,
				initialValue));
		McpDialogSession session = new McpDialogSession(title == null ? "Select paths" : title, fields);
		McpDialogRegistry.setCurrent(session);
		String value = waitForValue(session, LABEL_MULTI);
		McpDialogRegistry.setCurrent(null);
		String normalized = normalizeValue(value);
		if (normalized == null) {
			return null;
		}
		String[] parts = normalized.split("[\\r\\n;,]+");
		List<String> paths = new ArrayList<String>();
		for (String part : parts) {
			String trimmed = part.trim();
			if (!trimmed.isEmpty()) {
				paths.add(trimmed);
			}
		}
		if (paths.isEmpty()) {
			return null;
		}
		return paths.toArray(new String[0]);
	}

	private static String waitForValue(McpDialogSession session, String label) {
		String value = null;
		long deadline = System.currentTimeMillis() + TIMEOUT_MS;
		while (System.currentTimeMillis() < deadline) {
			value = session.getValue(label);
			if (value != null && !value.trim().isEmpty()) {
				break;
			}
			try {
				Thread.sleep(POLL_MS);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				break;
			}
		}
		return value;
	}

	private static String normalizeValue(String value) {
		if (value == null) {
			return null;
		}
		String trimmed = value.trim();
		return trimmed.isEmpty() ? null : trimmed;
	}
}
