package Visual_DVM_2021.Passes.All;
import Common.Current;
import Common.Global;
import Common.Utils.Utils;
import GlobalData.Account.AccountRole;
import Repository.Component.Component;
import Repository.Component.UI.PublishForm;
import Repository.EmailMessage;
import Repository.RepositoryServer;
import Repository.Server.ServerCode;
import Repository.Server.ServerExchangeUnit_2021;
import Visual_DVM_2021.Passes.ComponentsRepositoryPass;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;

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 (!Global.isWindows) {
            Log.Writeln_("Публикация компонент разрешена только для Windows");
            return false;
        }
        if (!Current.HasAccount()) {
            Log.Writeln_("Окно компонент было открыто до синхронизации прав");
            return false;
        }
        if (!Current.getAccount().role.equals(AccountRole.Admin)) {
            Log.Writeln_("Вы не являетесь администратором");
        }
        ;
        if (Current.Check(Log, Current.Component)) {
            target = Current.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 (f.ShowDialog(code().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())) + ":",
                Current.getAccount().name + Utils.RBrackets(Current.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.packFile(target.getFile())
        ));
        if (target.needs_update_minimal_version) {
            packed = target.getComponentType().toString() + "\n" +
                    target.getVersionText() + "\n";
            //--
            Command(new ServerExchangeUnit_2021(ServerCode.UpdateComponentMinimalVersion,
                    packed, Utils.packFile(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());
            Pass_2021.passes.get(PassCode_2021.Email).Do(message);
        }
    }
    @Override
    protected void showDone() throws Exception {
        Global.RefreshUpdatesStatus();
    }
}

