package io.xpipe.app.terminal;

import io.xpipe.app.issue.ErrorEventFactory;
import io.xpipe.app.process.ShellControl;
import io.xpipe.app.process.ShellDialect;
import io.xpipe.app.process.ShellTemp;
import io.xpipe.app.process.ShellTerminalInitCommand;
import io.xpipe.app.storage.DataStorage;
import io.xpipe.app.storage.DataStoreEntry;
import io.xpipe.app.util.FilePath;

import com.fasterxml.jackson.annotation.JsonTypeInfo;

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

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
public interface TerminalPrompt {

    static List<Class<?>> getClasses() {
        var l = new ArrayList<Class<?>>();
        l.add(StarshipTerminalPrompt.class);
        l.add(OhMyPoshTerminalPrompt.class);
        l.add(OhMyZshTerminalPrompt.class);
        return l;
    }

    String getDocsLink();

    default FilePath getConfigurationDirectory(ShellControl sc) throws Exception {
        var d = ShellTemp.createUserSpecificTempDataDirectory(sc, "prompt").join(getId());
        sc.view().mkdir(d);
        return d;
    }

    default FilePath getBinaryDirectory(ShellControl sc) throws Exception {
        var d = ShellTemp.createUserSpecificTempDataDirectory(sc, "bin").join(getId());
        sc.view().mkdir(d);
        return d;
    }

    String getId();

    default boolean installIfNeeded(ShellControl sc) throws Exception {
        if (!checkIfInstalled(sc)) {
            try {
                checkCanInstall(sc);
                install(sc);
            } catch (Exception e) {
                var name = sc.getSourceStoreId()
                        .flatMap(uuid -> DataStorage.get().getStoreEntryIfPresent(uuid))
                        .map(DataStoreEntry::getName)
                        .orElse(null);
                ErrorEventFactory.fromThrowable(e)
                        .omit()
                        .description("Prompt installation for " + getId() + " failed on remote system"
                                + (name != null ? " " + name : ""))
                        .expected()
                        .handle();
                return false;
            }
            return true;
        }
        return true;
    }

    void checkCanInstall(ShellControl sc) throws Exception;

    boolean checkIfInstalled(ShellControl sc) throws Exception;

    void install(ShellControl sc) throws Exception;

    ShellTerminalInitCommand terminalCommand() throws Exception;

    List<ShellDialect> getSupportedDialects();
}
