package io.xpipe.app.prefs;

import io.xpipe.app.comp.BaseRegionBuilder;
import io.xpipe.app.comp.base.ButtonComp;
import io.xpipe.app.core.AppI18n;
import io.xpipe.app.platform.LabelGraphic;
import io.xpipe.app.platform.OptionsBuilder;
import io.xpipe.app.platform.OptionsChoiceBuilder;
import io.xpipe.app.pwman.PasswordManager;
import io.xpipe.app.util.*;

import javafx.beans.binding.Bindings;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;

import org.kordamp.ikonli.javafx.FontIcon;

public class PasswordManagerCategory extends AppPrefsCategory {

    public static OptionsBuilder passwordManagerChoice() {
        var prefs = AppPrefs.get();

        var choiceBuilder = OptionsChoiceBuilder.builder()
                .property(prefs.passwordManager)
                .available(PasswordManager.getClasses())
                .allowNull(true)
                .transformer(entryComboBox -> {
                    var websiteLinkButton =
                            new ButtonComp(AppI18n.observable("website"), new FontIcon("mdi2w-web"), () -> {
                                var l = prefs.passwordManager.getValue().getWebsite();
                                if (l != null) {
                                    Hyperlinks.open(l);
                                }
                            });
                    websiteLinkButton.minWidth(Region.USE_PREF_SIZE);
                    websiteLinkButton.disable(Bindings.createBooleanBinding(
                            () -> {
                                return prefs.passwordManager.getValue() == null
                                        || prefs.passwordManager.getValue().getWebsite() == null;
                            },
                            prefs.passwordManager));

                    var hbox = new HBox(entryComboBox, websiteLinkButton.build());
                    HBox.setHgrow(entryComboBox, Priority.ALWAYS);
                    hbox.setSpacing(10);
                    return hbox;
                })
                .build();
        var choice = choiceBuilder.build().buildComp().maxWidth(600);

        return new OptionsBuilder().pref(prefs.passwordManager).addComp(choice);
    }

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

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

    @Override
    protected BaseRegionBuilder<?, ?> create() {
        var prefs = AppPrefs.get();
        return new OptionsBuilder()
                .title("passwordManager")
                .sub(passwordManagerChoice(), prefs.passwordManager)
                .buildComp();
    }
}
