package Visual_DVM_2021.UI.Main;
import Common.Current;
import Common.Global;
import Common.UI.Editor.BaseEditor;
import Common.UI.Editor.Viewer;
import Common.UI.Menus_2023.VisualiserMenuBar;
import Common.UI.TextField.StyledTextField;
import Common.UI.UI;
import Common.Utils.Utils;
import GlobalData.Settings.SettingName;
import Repository.BugReport.BugReport;
import Repository.BugReport.BugReportInterface;
import Repository.BugReport.BugReportState;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;
import Visual_DVM_2021.UI.Interface.CallbackWindow;
import Visual_DVM_2021.UI.Interface.CommentInterface;
import Visual_DVM_2021.UI.Interface.DescriptionInterface;
import Visual_DVM_2021.UI.Interface.FormWithSplitters;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class CallbackForm implements FormWithSplitters, CallbackWindow {
    private final JScrollPane bugCommentScroll;
    private final JScrollPane bugReportCommentAdditionScroll;
    private final BaseEditor BugReportComment;
    private final BaseEditor BugReportCommentAddition;
    //-------------------------------------------
    private final JScrollPane bugDescriptionScroll;
    private final JScrollPane bugReportDescriptionAdditionScroll;
    private final BaseEditor BugReportDescription;
    private final BaseEditor BugReportDescriptionAddition;
    private JPanel content;
    public JSplitPane SC10;
    public DescriptionInterface descriptionInterface;
    public CommentInterface commentInterface;
    DocumentListener descriptionAdditionListener = new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
        }
        @Override
        public void insertUpdate(DocumentEvent e) {
        }
        @Override
        public void changedUpdate(DocumentEvent e) {
            if (!Current.getBugReport().state.equals(BugReportState.draft))
                Current.getBugReport().descriptionAdditionDraft =
                        BugReportDescriptionAddition.getText();
        }
    };
    DocumentListener commentAdditionListener = new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
        }
        @Override
        public void insertUpdate(DocumentEvent e) {
        }
        @Override
        public void changedUpdate(DocumentEvent e) {
            if (!Current.getBugReport().state.equals(BugReportState.draft))
                Current.getBugReport().commentAdditionDraft = BugReportCommentAddition.getText();
        }
    };
    DocumentListener descriptionListener = new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
        }
        @Override
        public void insertUpdate(DocumentEvent e) {
        }
        @Override
        public void changedUpdate(DocumentEvent e) {
            if (Current.getBugReport().state.equals(BugReportState.draft))
                Current.getBugReport().description =
                        BugReportDescription.getText();
            Global.componentsServer.db.bugReports.RefreshUI();
        }
    };
    DocumentListener commentListener = new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
        }
        @Override
        public void insertUpdate(DocumentEvent e) {
        }
        @Override
        public void changedUpdate(DocumentEvent e) {
            if (Current.getBugReport().state.equals(BugReportState.draft))
                Current.getBugReport().comment = BugReportComment.getText();
        }
    };
    //-
    private JToolBar accountTools;
    private JLabel lAccountName;
    private JLabel lAccountMail;
    private JLabel lAccountRole;
    private JPanel accountPanel;
    private JPanel bugReportsPanel;
    private JPanel filterFormPanel;
    private JPanel subscribersPanel;
    private JTabbedPane currentBugReportTabs;
    private JScrollPane bugSettingsScroll;
    private JCheckBox BugReportsMyOnlyFilter;
    private JCheckBox BugReportsOpenedOnly;
    private JToolBar bugsTools;
    private JToolBar settingsTools;
    private JToolBar descriptionTools;
    private JToolBar commentTools;
    private JToolBar descriptionAdditionTools;
    private JToolBar commentAdditionTools;
    private JPanel descriptionPanel;
    private JPanel commentPanel;
    private JSplitPane SCX;
    public JSplitPane SC6;
    private JTextField BugReportsKeyFilter;
    private JTextField BugReportsSenderNameFilter;
    private JTextField BugReportsDescriptionFilter;
    private JTextField BugReportsVersionFilter;
    private JTextField BugReportsExecutorFilter;
    private JTextField BugReportsCommentFilter;
    private Viewer BugReportSettings;
    public void LockMyOnly() {
        if (!BugReportsMyOnlyFilter.isSelected()) {
            BugReportsMyOnlyFilter.doClick();
        }
        BugReportsMyOnlyFilter.setEnabled(false);
    }
    public void UnlockMyOnly() {
        BugReportsMyOnlyFilter.setEnabled(true);
        if (BugReportsMyOnlyFilter.isSelected()) {
            BugReportsMyOnlyFilter.doClick();
        }
    }
    public CallbackForm() {
        LoadSplitters();
        //---------------------------------
        //чтобы не было индусятины, лучше создать контролы здесь
        BugReportDescription = new BaseEditor();
        BugReportDescription.setLineWrap(true);
        bugDescriptionScroll = new JScrollPane(BugReportDescription);
        //----------------------------------------------
        BugReportDescriptionAddition = new BaseEditor();
        BugReportDescriptionAddition.setLineWrap(true);
        bugReportDescriptionAdditionScroll = new JScrollPane(BugReportDescriptionAddition);
        BugReportDescription.setWrapStyleWord(true);
        BugReportDescriptionAddition.setWrapStyleWord(true);
        //---------------------------------------------
        //-
        BugReportComment = new BaseEditor();
        BugReportComment.setLineWrap(true);
        bugCommentScroll = new JScrollPane(BugReportComment);
        //-
        BugReportCommentAddition = new BaseEditor();
        BugReportCommentAddition.setLineWrap(true);
        bugReportCommentAdditionScroll = new JScrollPane(BugReportCommentAddition);
        BugReportComment.setWrapStyleWord(true);
        BugReportCommentAddition.setWrapStyleWord(true);
        //----------------------------------------------
        //тут развилка на то вкладки или поля.
        SwitchScreen(Global.db.settings.get(SettingName.SmallScreen).toBoolean());
        //-
        Global.componentsServer.db.bugReports.mountUI(bugReportsPanel);
        Global.componentsServer.db.subscribers.mountUI(subscribersPanel);
        settingsTools.add(Pass_2021.passes.get(PassCode_2021.ApplyBugReportSettings).createButton());
        //-
        if (!Pass_2021.passes.get(PassCode_2021.CheckAccount).isDone()) {
            accountTools.add(Pass_2021.passes.get(PassCode_2021.CheckAccount).createButton());
        }
        //--
        BugReportsKeyFilter.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                BugReportInterface.filterKey = BugReportsKeyFilter.getText();
                ShowBugReports();
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
                BugReportInterface.filterKey = BugReportsKeyFilter.getText();
                ShowBugReports();
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });
        BugReportsSenderNameFilter.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                BugReportInterface.filterSenderName = BugReportsSenderNameFilter.getText();
                ShowBugReports();
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
                BugReportInterface.filterSenderName = BugReportsSenderNameFilter.getText();
                ShowBugReports();
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });
        BugReportsDescriptionFilter.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                BugReportInterface.filterDescription = BugReportsDescriptionFilter.getText();
                ShowBugReports();
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
                BugReportInterface.filterDescription = BugReportsDescriptionFilter.getText();
                ShowBugReports();
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });
        //------->>>
        BugReportsCommentFilter.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                BugReportInterface.filterComment = BugReportsCommentFilter.getText();
                ShowBugReports();
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
                BugReportInterface.filterComment = BugReportsCommentFilter.getText();
                ShowBugReports();
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });
        BugReportsExecutorFilter.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                BugReportInterface.filterExecutor = BugReportsExecutorFilter.getText();
                ShowBugReports();
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
                BugReportInterface.filterExecutor = BugReportsExecutorFilter.getText();
                ShowBugReports();
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });
        BugReportsVersionFilter.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                BugReportInterface.filterVersion = BugReportsVersionFilter.getText();
                ShowBugReports();
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
                BugReportInterface.filterVersion = BugReportsVersionFilter.getText();
                ShowBugReports();
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });
        //--------
        BugReportsMyOnlyFilter.addActionListener(e -> {
            BugReportInterface.filterMyOnly = BugReportsMyOnlyFilter.isSelected();
            ShowBugReports();
        });
        BugReportsOpenedOnly.addActionListener(e -> {
            BugReportInterface.filterOpenedOnly = BugReportsOpenedOnly.isSelected();
            ShowBugReports();
        });
    }
    //-------------------------------------------
    DescriptionTabs descriptionTabs = new DescriptionTabs();
    DescriptionFields descriptionFields = new DescriptionFields();
    CommentTabs commentTabs = new CommentTabs();
    CommentFields commentFields = new CommentFields();
    @Override
    public void SwitchScreen(boolean small) {
        UI.Clear(descriptionPanel);
        //------------------------------------------------------------------
        descriptionInterface = small ? descriptionTabs : descriptionFields;
        descriptionInterface.setEditorScroll(bugDescriptionScroll);
        descriptionInterface.setAdditionScroll(bugReportDescriptionAdditionScroll);
        descriptionPanel.add(descriptionInterface.getContent());
        //----------
        descriptionPanel.revalidate();
        descriptionPanel.repaint();
        //---------
        UI.Clear(commentPanel);
        //------------------------------------------------------------------
        commentInterface = small ? commentTabs : commentFields;
        commentInterface.setEditorScroll(bugCommentScroll);
        commentInterface.setAdditionScroll(bugReportCommentAdditionScroll);
        commentPanel.add(commentInterface.getContent());
        //----------
        commentPanel.revalidate();
        commentPanel.repaint();
    }
    @Override
    public void SaveSplitters() {
        FormWithSplitters.super.SaveSplitters();
        descriptionInterface.SaveSplitters();
        commentInterface.SaveSplitters();
    }
    @Override
    public String getBugReportDescriptionText() {
        return BugReportDescription.getText();
    }
    @Override
    public String getBugReportDescriptionAdditionText() {
        return BugReportDescriptionAddition.getText();
    }
    @Override
    public String getBugReportCommentText() {
        return BugReportComment.getText();
    }
    @Override
    public String getBugReportCommentAdditionText() {
        return BugReportCommentAddition.getText();
    }
    @Override
    public void ClearBugReportDescriptionAdditionText() {
        BugReportDescriptionAddition.setText("");
    }
    @Override
    public void ClearBugReportCommentAdditionText() {
        BugReportCommentAddition.setText("");
    }
    @Override
    public void FocusRecipients() {
        currentBugReportTabs.setSelectedIndex(2);
    }
    public void SwitchListeners(boolean on) {
        //System.out.println("switching listeners " + on);
        if (on) {
            BugReportDescriptionAddition.getDocument().addDocumentListener(descriptionAdditionListener);
            BugReportCommentAddition.getDocument().addDocumentListener(commentAdditionListener);
            BugReportDescription.getDocument().addDocumentListener(descriptionListener);
            BugReportComment.getDocument().addDocumentListener(commentListener);
        } else {
            BugReportDescriptionAddition.getDocument().removeDocumentListener(descriptionAdditionListener);
            BugReportCommentAddition.getDocument().removeDocumentListener(commentAdditionListener);
            BugReportDescription.getDocument().removeDocumentListener(descriptionListener);
            BugReportComment.getDocument().removeDocumentListener(commentListener);
        }
    }
    private void createUIComponents() {
        BugReportSettings = new Viewer();
        bugSettingsScroll = new JScrollPane(BugReportSettings);
        //--
        BugReportsKeyFilter = new StyledTextField();
        BugReportsSenderNameFilter = new StyledTextField();
        BugReportsDescriptionFilter = new StyledTextField();
        BugReportsCommentFilter = new StyledTextField();
        BugReportsExecutorFilter = new StyledTextField();
        BugReportsVersionFilter = new StyledTextField();
        settingsTools = new VisualiserMenuBar();
    }
    public void EnableBugreports() {
        UI.Clear(accountPanel);
        accountPanel.add(SC10);
        UI.getMainWindow().ShowTestingTab();
    }
    @Override
    public void setUserRights() {
        LockMyOnly();
        Pass_2021.passes.get(PassCode_2021.AddSubscriber).setControlsVisible(false);
        Pass_2021.passes.get(PassCode_2021.EditSubscriber).setControlsVisible(false);
        Pass_2021.passes.get(PassCode_2021.DeleteSubscriber).setControlsVisible(false);
        Pass_2021.passes.get(PassCode_2021.DownloadAllBugReportsArchives).setControlsVisible(false);
    }
    private void setDeveloperRights() {
        UnlockMyOnly();
        Pass_2021.passes.get(PassCode_2021.AddSubscriber).setControlsVisible(false);
        Pass_2021.passes.get(PassCode_2021.EditSubscriber).setControlsVisible(false);
        Pass_2021.passes.get(PassCode_2021.DeleteSubscriber).setControlsVisible(false);
        Pass_2021.passes.get(PassCode_2021.DownloadAllBugReportsArchives).setControlsVisible(true);
    }
    @Override
    public void setAdminRights() {
        UnlockMyOnly();
        Pass_2021.passes.get(PassCode_2021.AddSubscriber).setControlsVisible(true);
        Pass_2021.passes.get(PassCode_2021.EditSubscriber).setControlsVisible(true);
        Pass_2021.passes.get(PassCode_2021.DeleteSubscriber).setControlsVisible(true);
        Pass_2021.passes.get(PassCode_2021.DownloadAllBugReportsArchives).setControlsVisible(true);
    }
    @Override
    public void ShowAccount() {
        lAccountName.setText(Utils.Brackets(Current.getAccount().name));
        lAccountMail.setText(Utils.Brackets(Current.getAccount().email));
        lAccountRole.setText(Utils.Brackets(Current.getAccount().role.getDescription()));
        switch (Current.getAccount().role) {
            case Undefined:
                UI.Clear(accountPanel);
                accountPanel.add(new CallbackWelcomeForm().content);
                UI.getMainWindow().HideTestingTab();
                break;
            case User:
                //видит только свои баги.
                EnableBugreports();
                setUserRights();
                break;
            case Developer:
                EnableBugreports();
                setDeveloperRights();
                break;
            case Admin:
                EnableBugreports();
                setAdminRights();
                break;
            default:
                EnableBugreports();
                break;
        }
    }
    @Override
    public void ShowBugReports() {
        Global.componentsServer.db.bugReports.ShowUI();
    }
    @Override
    public void ShowNoBugReports() {
        Global.componentsServer.db.bugReports.ClearUI();
    }
    @Override
    public void ShowSubscribers() {
        Global.componentsServer.db.subscribers.ShowUI();
    }
    @Override
    public void ShowNoSubscribers() {
        Global.componentsServer.db.subscribers.ClearUI();
    }
    private void ShowDraft() {
        Pass_2021.setPassesControlsVisible(true,
                PassCode_2021.PublishBugReport,
                PassCode_2021.SaveBugReportRecipients,
                PassCode_2021.SaveBugReportExecutor,
                PassCode_2021.DeleteBugReport
        );
        Pass_2021.setPassesControlsVisible(false,
                PassCode_2021.AppendBugReportDescription,
                PassCode_2021.AppendBugReportComment,
                PassCode_2021.SaveBugReportDescription,
                PassCode_2021.SaveBugReportComment,
                PassCode_2021.OpenBugReport,
                PassCode_2021.CloseBugReport,
                PassCode_2021.OpenBugReportTestProject,
                PassCode_2021.UpdateBugReportProgress
        );
    }
    private void ShowUserExecutor() {
        Pass_2021.setPassesControlsVisible(true,
                PassCode_2021.AppendBugReportComment,
                PassCode_2021.UpdateBugReportProgress,
                PassCode_2021.OpenBugReportTestProject
        );
        Pass_2021.setPassesControlsVisible(false,
                PassCode_2021.PublishBugReport,
                PassCode_2021.SaveBugReportRecipients,
                PassCode_2021.SaveBugReportExecutor,
                PassCode_2021.SaveBugReportDescription,
                PassCode_2021.SaveBugReportComment,
                PassCode_2021.AppendBugReportDescription,
                PassCode_2021.OpenBugReport,
                PassCode_2021.CloseBugReport,
                PassCode_2021.DeleteBugReport
        );
    }
    private void ShowSender() {
        Pass_2021.setPassesControlsVisible(true,
                PassCode_2021.AppendBugReportComment,
                PassCode_2021.UpdateBugReportProgress,
                PassCode_2021.OpenBugReportTestProject,
                PassCode_2021.SaveBugReportRecipients,
                PassCode_2021.SaveBugReportExecutor,
                PassCode_2021.SaveBugReportDescription,
                PassCode_2021.SaveBugReportComment,
                PassCode_2021.AppendBugReportDescription,
                PassCode_2021.OpenBugReport,
                PassCode_2021.CloseBugReport,
                PassCode_2021.DeleteBugReport
        );
        Pass_2021.setPassesControlsVisible(false,
                PassCode_2021.PublishBugReport
        );
    }
    private void ShowUser() {
        Pass_2021.setPassesControlsVisible(false,
                PassCode_2021.PublishBugReport,
                PassCode_2021.SaveBugReportRecipients,
                PassCode_2021.SaveBugReportExecutor,
                PassCode_2021.SaveBugReportDescription,
                PassCode_2021.SaveBugReportComment,
                PassCode_2021.AppendBugReportDescription,
                PassCode_2021.OpenBugReport,
                PassCode_2021.CloseBugReport,
                PassCode_2021.DeleteBugReport,
                PassCode_2021.AppendBugReportComment,
                PassCode_2021.UpdateBugReportProgress,
                PassCode_2021.OpenBugReportTestProject
        );
    }
    @Override
    public void ShowCurrentBugReport() {
        SwitchListeners(false);
        // currentBugReportTabs.setSelectedIndex(0);
        BugReport target = Current.getBugReport();
        BugReportInterface.CheckSubscribers(target);
        Global.componentsServer.db.subscribers.ShowUI();
        //-
        BugReportDescription.setText(target.description);
        BugReportDescription.ShowBegin();
        BugReportDescriptionAddition.setText(target.descriptionAdditionDraft);
        //-
        BugReportComment.setText(target.comment);
        BugReportComment.ShowBegin();
        BugReportCommentAddition.setText(target.commentAdditionDraft);
        BugReportSettings.setText(
                String.join("\n",
                        ("Версия SAPFOR: " + target.sapfor_version),
                        ("Версия визуализатора: " + target.visualiser_version),
                        target.sapfor_settings
                )
        );
        Pass_2021.setPassesControlsVisible(true, PassCode_2021.ApplyBugReportSettings);
        //
        if (target.state.equals(BugReportState.draft)) {
            ShowDraft();
        } else {
            switch (Current.getAccount().role) {
                case User:
                    if (Current.getAccount().email.equalsIgnoreCase(target.sender_address)) {
                        ShowSender();  //отправитель.может делать с багом все.
                    } else {
                        if (Current.getAccount().email.equalsIgnoreCase(target.executor_address)) {
                            ShowUserExecutor(); //исполнитель. может менять прогресс и дополнять комментарий.
                        } else ShowUser(); //недоступно ничего. и баг ему невидим. но на всякий случай.
                    }
                    break;
                case Developer:
                case Admin:
                    //разработчик может все то же что и админ. они равны по правам владельцу любого бага.
                    ShowSender();
                    break;
            }
        }
        SwitchListeners(true);
    }
    @Override
    public void ShowNoCurrentBugReport() {
        SwitchListeners(false);
        Global.componentsServer.db.subscribers.ShowUI();
        //-
        BugReportDescription.setText("");
        BugReportComment.setText("");
        BugReportDescriptionAddition.setText("");
        BugReportCommentAddition.setText("");
        BugReportSettings.setText("");
        //-
        Pass_2021.setPassesControlsVisible(false, PassCode_2021.SaveBugReportExecutor,
                PassCode_2021.SaveBugReportRecipients,
                PassCode_2021.AppendBugReportDescription,
                PassCode_2021.SaveBugReportDescription,
                PassCode_2021.SaveBugReportComment,
                PassCode_2021.AppendBugReportComment,
                PassCode_2021.ApplyBugReportSettings,
                PassCode_2021.PublishBugReport,
                PassCode_2021.OpenBugReport,
                PassCode_2021.CloseBugReport,
                PassCode_2021.OpenBugReportTestProject,
                PassCode_2021.UpdateBugReportProgress,
                PassCode_2021.DeleteBugReport
        );
    }
    @Override
    public void ShowSubscription() {
    }
    @Override
    public JPanel getContent() {
        return content;
    }
}
