package com.fr.design.file;

import com.fr.design.gui.icheckbox.UICheckBox;
import com.fr.design.gui.icontainer.UIScrollPane;
import com.fr.design.gui.ilable.UILabel;
import com.fr.design.gui.ilist.UIList;
import com.fr.design.layout.FRGUIPaneFactory;
import com.fr.design.mainframe.DesignerContext;
import com.fr.design.mainframe.JTemplate;
import com.fr.design.dialog.BasicDialog;
import com.fr.design.dialog.BasicPane;
import com.fr.design.dialog.DialogActionAdapter;
import com.fr.general.ComparatorUtils;
import com.fr.general.FRLogger;
import com.fr.general.Inter;
import com.fr.stable.ProductConstants;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.logging.Level;

/**
 * Author : daisy
 * Date: 13-8-9
 * Time: 下午3:41
 */
public class SaveSomeTemplatePane extends BasicPane {

    private UICheckBox[] templateCheckBoxes = null;
    private BasicDialog dialog;
    private JPanel templatesChoosePane;
    private UIScrollPane scrollPane;
    private java.util.List<JTemplate<?, ?>> unSavedTemplate = new ArrayList<JTemplate<?, ?>>();
    private boolean isAllSaved = false;

    //该变量用来判断是在关闭其他模板或是关闭设计器的时候，是否需要判断当前模板有没有保存
    private boolean isJudgeCurrentEditingTemplate = true;

    public SaveSomeTemplatePane(boolean isNeedTojudgeCurrent) {
        this.setLayout(FRGUIPaneFactory.createBorderLayout());
        if (this.dialog == null) {
            this.dialog = this.showSmallWindow(DesignerContext.getDesignerFrame(), new DialogActionAdapter() {
                @Override
                public void doOk() {
                    for (int i = 0; i < templateCheckBoxes.length; i++) {
                        if (templateCheckBoxes[i].isSelected()) {
                            saveSelectedTemplate(unSavedTemplate.get(i));
                        }
                    }
                    isAllSaved = true;
                }

                public void doCancel() {
                    isAllSaved = false;
                }

            });
        }
        UILabel tip = new UILabel(Inter.getLocText("Select_The_Source_To_Save"));
        this.add(tip, BorderLayout.NORTH);
        templatesChoosePane = FRGUIPaneFactory.createBorderLayout_S_Pane();
        UIScrollPane scrollPane = new UIScrollPane(templatesChoosePane);
        this.add(scrollPane, BorderLayout.CENTER);
        this.isJudgeCurrentEditingTemplate = isNeedTojudgeCurrent;
    }

    private void initTemplatesChoosePane() {
        templatesChoosePane.setBorder(BorderFactory.createTitledBorder(""));
        for (int i = 0; i < unSavedTemplate.size(); i++) {
            templateCheckBoxes[i] = new UICheckBox(unSavedTemplate.get(i).getEditingFILE().getName());
            templateCheckBoxes[i].setSelected(true);
        }
        final UIList templatesList = new UIList(templateCheckBoxes);
        templatesList.setModel(new UnSeletedTemplateListDataMode());
        templatesList.setCellRenderer(new UnSelectedListCellRender());
        templatesList.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                super.mousePressed(e);
                int index = templatesList.getSelectedIndex();
                if (index < 0) {
                    return;
                }
                UICheckBox checkBox = (UICheckBox) templatesList.getModel().getElementAt(index);
                checkBox.setSelected(!checkBox.isSelected());
                templatesList.repaint();
            }
        });

        final UICheckBox filenameCheckBox = new UICheckBox(Inter.getLocText("Choose_All"));
        filenameCheckBox.setSelected(true);
        filenameCheckBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                boolean isSelected = filenameCheckBox.isSelected();
                for (int i = 0; i < templatesList.getModel().getSize(); i++) {
                    UICheckBox checkBox = (UICheckBox) templatesList.getModel().getElementAt(i);
                    checkBox.setSelected(isSelected);
                }
                templatesList.repaint();
            }
        });
        templatesChoosePane.add(filenameCheckBox, BorderLayout.NORTH);
        templatesChoosePane.add(templatesList, BorderLayout.CENTER);

    }


    public boolean showSavePane() {
        populate();
        //如果有未保存的文件 ，则跳出保存对话框，选择要存储的项目
        if (!unSavedTemplate.isEmpty()) {
            dialog.setVisible(true);
        } else {
            isAllSaved = true;
        }
        return isAllSaved;
    }

    public void populate() {
        java.util.List<JTemplate<?, ?>> opendedTemplate = HistoryTemplateListPane.getInstance().getHistoryList();
        JTemplate<?, ?> currentTemplate = HistoryTemplateListPane.getInstance().getCurrentEditingTemplate();
        for (int i = 0; i < opendedTemplate.size(); i++) {
            if (isneedToAdd(opendedTemplate.get(i), currentTemplate)) {
                unSavedTemplate.add(opendedTemplate.get(i));
            }
        }
        templateCheckBoxes = new UICheckBox[unSavedTemplate.size()];
        initTemplatesChoosePane();
    }

    private boolean isneedToAdd(JTemplate<?, ?> template, JTemplate<?, ?> currentTemplate) {
        //所有模板都判断是不是保存
        if (isJudgeCurrentEditingTemplate) {
            return !template.isALLSaved();
        }

        //当前编辑的模板不判断是否已经保存
        if (ComparatorUtils.equals(template, currentTemplate)) {
            return false;
        } else {
            return !template.isALLSaved();
        }
    }


    private void saveSelectedTemplate(JTemplate<?, ?> specifiedTemplate) {
        if (!specifiedTemplate.isSaved()) {
            specifiedTemplate.stopEditing();
            specifiedTemplate.saveTemplate();
        }
        FRLogger.getLogger().log(Level.INFO, Inter.getLocText(new String[]{"Template", "already-saved"}, new String[]{specifiedTemplate.getEditingFILE().getName(), "."}));
    }


    public int saveLastOneTemplate() {
        JTemplate<?, ?> specifiedTemplate = HistoryTemplateListPane.getInstance().getCurrentEditingTemplate();
        if (!specifiedTemplate.isALLSaved()) {
            specifiedTemplate.stopEditing();
            int returnVal = JOptionPane.showConfirmDialog(DesignerContext.getDesignerFrame(), Inter.getLocText("Utils-Would_you_like_to_save") + " \"" + specifiedTemplate.getEditingFILE() + "\" ?",
                    ProductConstants.PRODUCT_NAME, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (returnVal == JOptionPane.YES_OPTION && specifiedTemplate.saveTemplate()) {
                specifiedTemplate.saveTemplate();
                FRLogger.getLogger().log(Level.INFO, Inter.getLocText(new String[]{"Template", "already-saved"}, new String[]{specifiedTemplate.getEditingFILE().getName(), "."}));
            }
            return returnVal;
        }
        return JOptionPane.YES_OPTION;
    }


    protected String title4PopupWindow() {
        return Inter.getLocText("Save");
    }


    private class UnSelectedListCellRender extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, final boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            templateCheckBoxes[index] = (UICheckBox) value;
            templateCheckBoxes[index].setBackground(list.getBackground());
            return templateCheckBoxes[index];
        }

    }


    private class UnSeletedTemplateListDataMode extends AbstractListModel {

        @Override
        public int getSize() {
            return templateCheckBoxes.length;
        }

        @Override
        public UICheckBox getElementAt(int index) {
            if (index > getSize() - 1 || index < 0) {
                return null;
            }
            return templateCheckBoxes[index];
        }

    }


}