package _VisualDVM.Passes.All;
import Common.Utils.Pair;
import Common.Utils.Utils_;
import _VisualDVM.ComponentsServer.BugReport.BugReport;
import _VisualDVM.ComponentsServer.BugReport.BugReportState;
import _VisualDVM.Global;
import _VisualDVM.Passes.PassCode;
import _VisualDVM.Passes.Server.ComponentsServerPass;
import _VisualDVM.Repository.EmailMessage;
import _VisualDVM.Repository.Server.ServerCode;
import _VisualDVM.Utils;

import java.io.Serializable;
import java.util.Date;
import java.util.Vector;
public class UpdateBugReportField extends ComponentsServerPass<BugReport> {
    Vector<String> fieldNames = new Vector<>();
    Vector<Serializable> fieldValues = new Vector<>();
    String old_description = "";
    String old_comment = "";
    BugReport actual;
    protected boolean canUpdate() {
        return target.canModify(Global.mainModule.getAccount(), Log);
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        actual = null;
        if (!Global.componentsServer.db.bugReports.getUI().CheckCurrent(Log))
            return false;
        old_description = "";
        old_comment = "";
        //--
        target = Global.componentsServer.db.bugReports.getUI().getCurrent();
        fieldNames.clear();
        fieldValues.clear();
        for (int i = 0; i < args.length; ++i) {
            if (i % 2 == 0) {
                fieldNames.add((String) args[i]);
            } else {
                fieldValues.add((Serializable) args[i]);
            }
        }
        if (fieldNames.size() != fieldValues.size()) {
            Log.Writeln("Неверный формат аргументов");
            return false;
        }
        if (target.state.equals(BugReportState.draft)) {
            //если черновик, сразу меняем и не заморачиваемся, если нужно.
            //тут проход все равно сугубо интерфейсный.
            for (int i = 0; i < fieldNames.size(); ++i)
                BugReport.class.getField(fieldNames.get(i)).set(target, fieldValues.get(i));
            target.change_date = new Date().getTime();
            getServer().db.Update(target);
            getServer().db.bugReports.getUI().RedrawControl();
            Global.mainModule.getUI().getMainWindow().getCallbackWindow().ShowCurrentBugReport();
        } else {
            if (canUpdate() && SendRequest(ServerCode.GetObjectCopyByPK, "", new Pair<>(BugReport.class, target.id))) {
                actual = (BugReport) request.target;
                target.SynchronizeFields(actual);
                for (int i = 0; i < fieldNames.size(); ++i) {
                    String fieldName = fieldNames.get(i);
                    switch (fieldName) {
                        case "comment":
                            old_comment = (String) BugReport.class.getField(fieldName).get(target);
                            break;
                        case "description":
                            old_description = (String) BugReport.class.getField(fieldName).get(target);
                            break;
                    }
                    BugReport.class.getField(fieldNames.get(i)).set(target, fieldValues.get(i));
                }
                target.change_date = new Date().getTime();
                return SendRequest(ServerCode.UpdateBugReport, "", target);
            }
        }
        return false;
    }
    @Override
    protected void body() throws Exception {
        getServer().db.Update(target);
    }
    @Override
    protected void showFinish() throws Exception {
        Global.componentsServer.db.bugReports.getUI().RedrawControl();
        Global.mainModule.getUI().getMainWindow().getCallbackWindow().ShowCurrentBugReport();
    }
    @Override
    protected void performDone() throws Exception {
        String message_header = target.getMailTitlePrefix();

        /*
        String message_text = "DUMMY TEXT: ";
        Random random = new Random();
        for (int k = 0; k < random.nextInt(200); ++k)
            message_text += random.nextDouble();

         */
        String message_text = String.join("\n",
                target.description,
                target.comment);
        if (fieldNames.size() >= 1) {
            switch (fieldNames.get(0)) {
                case "sender_address":
                case "sender_name":
                case "targets":
                case "percentage":
                    return;
                case "description":
                    message_header += "описание изменено";
                    message_text = Utils.compareTexts(old_description, target.description);
                    break;
                case "comment":
                    message_header += "комментарий изменён";
                    message_text = Utils.compareTexts(old_comment, target.comment);
                    break;
                case "executor":
                    message_header += target.executor + " назначается исполнителем";
                    break;
                case "state":
                    message_header += "состояние изменилось на " + Utils_.Brackets(target.state.getDescription());
                    break;
            }
            EmailMessage message = new EmailMessage(
                    message_header + " " + Utils_.Brackets(Global.mainModule.getAccount().name),
                    message_text
            );

            Global.mainModule.getPass(PassCode.Email).Do(
                    message,
                    Global.componentsServer.db.recipients.getSelectedMails());
        }
    }
}
