package io.xpipe.app.prefs;

import io.xpipe.app.comp.BaseRegionBuilder;
import io.xpipe.app.comp.RegionBuilder;
import io.xpipe.app.comp.base.*;
import io.xpipe.app.core.AppFontSizes;
import io.xpipe.app.core.AppI18n;
import io.xpipe.app.platform.LabelGraphic;
import io.xpipe.app.platform.OptionsBuilder;
import io.xpipe.app.process.LocalShell;
import io.xpipe.app.storage.DataStorage;
import io.xpipe.app.storage.DataStorageSyncHandler;
import io.xpipe.app.terminal.TerminalLaunch;
import io.xpipe.app.util.*;
import io.xpipe.app.util.FilePath;

import javafx.beans.property.SimpleBooleanProperty;
import javafx.geometry.Pos;

import java.util.Arrays;
import java.util.List;

public class SyncCategory extends AppPrefsCategory {

    @Override
    protected String getId() {
        return "vaultSync";
    }

    @Override
    protected LabelGraphic getIcon() {
        return new LabelGraphic.IconGraphic("mdrmz-vpn_lock");
    }

    public BaseRegionBuilder<?, ?> create() {
        var prefs = AppPrefs.get();

        var testButton = new TestButtonComp(() -> {
            var r = DataStorageSyncHandler.getInstance().validateConnection();
            return r;
        });

        var remoteRepo = new TextFieldComp(prefs.storageGitRemote).hgrow();
        remoteRepo.apply(textField -> textField.setPromptText("https://... | ssh://... | directory path"));
        remoteRepo.disable(prefs.enableGitStorage.not());

        var builder = new OptionsBuilder();
        builder.title("gitSync")
                .sub(new OptionsBuilder()
                        .pref(prefs.enableGitStorage)
                        .addToggle(prefs.enableGitStorage)
                        .pref(prefs.storageGitRemote)
                        .addComp(remoteRepo.maxWidth(getCompWidth()), prefs.storageGitRemote)
                        .addComp(testButton)
                        .disable(prefs.storageGitRemote.isNull().or(prefs.enableGitStorage.not()))
                        .sub(prefs.getCustomOptions("syncToPlainDirectory"))
                        .sub(prefs.getCustomOptions("gitUsername"))
                        .sub(prefs.getCustomOptions("gitPassword"))
                        .sub(prefs.getCustomOptions("gitVaultIdentityStrategy"))
                        .pref(prefs.syncMode)
                        .addComp(
                                ChoiceComp.ofTranslatable(prefs.syncMode, Arrays.asList(SyncMode.values()), false)
                                        .maxWidth(getCompWidth()),
                                prefs.syncMode)
                        .addComp(createManualControls())
                        .hide(prefs.syncMode.isNotEqualTo(SyncMode.MANUAL).or(prefs.enableGitStorage.not()))
                        .nameAndDescription("browseVault")
                        .addComp(new ButtonComp(AppI18n.observable("browseVaultButton"), () -> {
                            DesktopHelper.browseFile(DataStorage.get().getStorageDir());
                        })));
        return builder.buildComp();
    }

    private RegionBuilder<?> createManualControls() {
        var busy = new SimpleBooleanProperty();
        var busyIcon = new LoadingIconComp(busy, AppFontSizes::base);

        var pullButton = new ButtonComp(
                AppI18n.observable("pullChanges"), new LabelGraphic.IconGraphic("mdi2d-download"), () -> {
                    ThreadHelper.runFailableAsync(() -> {
                        BooleanScope.executeExclusive(busy, () -> {
                            DataStorage.get().pullManually();
                        });
                    });
                });

        var pushButton =
                new ButtonComp(AppI18n.observable("pushChanges"), new LabelGraphic.IconGraphic("mdi2u-upload"), () -> {
                    ThreadHelper.runFailableAsync(() -> {
                        BooleanScope.executeExclusive(busy, () -> {
                            DataStorage.get().pushManually();
                        });
                    });
                });

        var terminalButton = new ButtonComp(
                AppI18n.observable("openTerminal"), new LabelGraphic.IconGraphic("mdi2c-console"), () -> {
                    ThreadHelper.runFailableAsync(() -> {
                        BooleanScope.executeExclusive(busy, () -> {
                            TerminalLaunch.builder()
                                    .command(LocalShell.getShell())
                                    .directory(FilePath.of(DataStorage.get().getStorageDir()))
                                    .launch();
                        });
                    });
                });

        var box = new HorizontalComp(List.of(pullButton, pushButton, terminalButton, busyIcon))
                .spacing(10)
                .apply(struc -> struc.setAlignment(Pos.CENTER_LEFT));
        return box;
    }
}
