package _VisualDVM.Passes.All;
import Common.Utils.Utils_;
import _VisualDVM.Current;
import _VisualDVM.Global;
import _VisualDVM.GlobalData.Account.AccountRole;
import _VisualDVM.Passes.PassCode;
import _VisualDVM.Passes.Server.ComponentsRepositoryPass;
import _VisualDVM.Repository.Component.Component;
import _VisualDVM.Repository.Component.ComponentType;
import _VisualDVM.Repository.Component.UI.PublishForm;
import _VisualDVM.Repository.EmailMessage;
import _VisualDVM.Repository.RepositoryServer;
import _VisualDVM.Repository.Server.ServerCode;
import _VisualDVM.Repository.Server.ServerExchangeUnit_2021;
import _VisualDVM.Visual.UI;

import java.util.Date;
import java.util.Vector;
public class PublishComponent extends ComponentsRepositoryPass<Component> {
    String version_mail_header = "";
    String version_text = "";
    PublishForm f = new PublishForm();
    @Override
    public String getIconPath() {
        return "/icons/Publish.png";
    }
    @Override
    public String getButtonText() {
        return "";
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        if (!Utils_.isWindows()) {
            Log.Writeln_("Публикация компонент разрешена только для Windows");
            return false;
        }
        if (!Global.mainModule.HasAccount()) {
            Log.Writeln_("Окно компонент было открыто до синхронизации прав");
            return false;
        }
        if (!Global.mainModule.getAccount().role.equals(AccountRole.Admin)) {
            Log.Writeln_("Вы не являетесь администратором");
        }
        ;
        if (Global.mainModule.Check(Log, Current.Component)) {
            target = Global.mainModule.getComponent();
            target.needs_update_minimal_version = false;
            f.fields.cbUpdateMinimalVersion.setSelected(false);
            f.fields.lMinimalVersion.setText(String.valueOf(target.minimal_version));
            f.fields.lPublishingVersion.setText(String.valueOf(target.version));
            if (!target.isValidVersion(Log, "публикуемого")) {
                return false;
            }
            if (target.getComponentType().equals(ComponentType.Sapfor_F)) {
                f.fields.cbAssemblyOnServer.setVisible(true);
                f.fields.cbAssemblyOnServer.setSelected(false);
            } else {
                f.fields.cbAssemblyOnServer.setVisible(false);
                f.fields.cbAssemblyOnServer.setSelected(false);
            }
            if (f.ShowDialog(getDescription())) {
                target.needs_update_minimal_version = f.fields.cbUpdateMinimalVersion.isSelected();
                return true;
            }
        }
        return false;
    }
    @Override
    protected void ServerAction() throws Exception {
        String change_description = (f.Result == null) ? "не указаны" : f.Result;
        String change_record_header = String.join(" ",
                Utils_.Brackets(Utils_.print_date(new Date())) + ":",
                Global.mainModule.getAccount().name + Utils_.RBrackets(Global.mainModule.getAccount().email),
                "публикует версию", Utils_.DQuotes(target.version)
        );
        String change_record = String.join("\n", change_record_header, "Изменения:",
                change_description,
                RepositoryServer.separator, ""
        );
        String packed =
                target.getComponentType().toString() + "\n" +
                        target.getFileName() + "\n" +
                        target.getVersionText() + "\n" +
                        change_record;
        Command(new ServerExchangeUnit_2021(ServerCode.PublishComponent,
                packed, Utils_.fileToBytes(target.getFile())
        ));
        if (target.needs_update_minimal_version) {
            packed = target.getComponentType().toString() + "\n" +
                    target.getVersionText() + "\n";
            //--
            Command(new ServerExchangeUnit_2021(ServerCode.UpdateComponentMinimalVersion,
                    packed, Utils_.fileToBytes(target.getFile())
            ));
        }
    }
    @Override
    protected void performDone() throws Exception {
        target.actual_version = target.version;
        target.CheckIfNeedsUpdateOrPublish();
        if ((f.Result != null)) {
            version_mail_header = String.join(" ",
                    "Опубликована версия",
                    Utils_.DQuotes(target.version),
                    "компонента",
                    Utils_.DQuotes(target.getComponentType().getDescription()));
            EmailMessage message =
                    new EmailMessage(version_mail_header,
                            f.Result,
                            new Vector<>(Global.componentsServer.db.subscribers.Data.keySet()));
            if (f.fields.cbForceMail.isSelected())
                message.addAttachement(target.getFile());
            Global.mainModule.getPass(PassCode.Email).Do(message);
            //---
            if (target.getComponentType().equals(ComponentType.Sapfor_F) && f.fields.cbAssemblyOnServer.isSelected()) {
                UI.getMainWindow().FocusTesting();
                UI.getMainWindow().getTestingWindow().FocusSapforTesting();
                Global.mainModule.getPass(PassCode.CompileServerSapfor).Do();
            }
        }
    }
    @Override
    protected void showDone() throws Exception {
        Global.RefreshUpdatesStatus();
    }
}

