/*
 * File    : CopyAttributesPanel.java
 * Created : 30-jun-2004 16:46
 * By      : fbusquets
 *
 * JClic - Authoring and playing system for educational activities
 *
 * Copyright (C) 2000 - 2018 Francesc Busquets & Departament
 * d'Educacio de la Generalitat de Catalunya
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details (see the LICENSE file).
 */

package edu.xtec.jclic;

import edu.xtec.jclic.activities.text.TextActivityBase;
import edu.xtec.jclic.activities.text.TextActivityDocument;
import edu.xtec.jclic.bags.ActivityBagEditor;
import edu.xtec.jclic.bags.ActivityBagElementEditor;
import edu.xtec.jclic.beans.CheckBoxTreeObject;
import edu.xtec.util.Options;
import edu.xtec.util.ProgressDialog;
import javax.swing.text.StyleContext;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;

/**
 * @author Francesc Busquets (fbusquets@xtec.cat)
 * @version 13.08.29
 */
public class CopyActivityAttributesPanel extends javax.swing.JPanel {

  Options options;
  ActivityBagElementEditor abed;
  ActivityBagEditor abe;

  /** Creates new form CopyActivityAttributesPanel */
  public CopyActivityAttributesPanel(Options options, ActivityBagElementEditor abed) {
    this.options = options;
    this.abed = abed;
    abe = (ActivityBagEditor) abed.getEditorParent();
    initComponents();
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  // <editor-fold defaultstate="collapsed" desc="Generated
  // Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    javax.swing.JScrollPane scroll = new javax.swing.JScrollPane();
    checkBoxTree = new edu.xtec.jclic.beans.CheckBoxTree();
    javax.swing.JPanel actPanel = new javax.swing.JPanel();
    javax.swing.JScrollPane actScroll = new javax.swing.JScrollPane();
    actList = new javax.swing.JList<Object>();
    selectAllBtn = new javax.swing.JButton();
    selectNoneBtn = new javax.swing.JButton();

    setLayout(new java.awt.BorderLayout());

    scroll.setPreferredSize(new java.awt.Dimension(300, 300));

    checkBoxTree.setModel(getTreeModel());
    int k = checkBoxTree.getRowCount();
    for (int i = k + 1; i >= 0; i--) {
      checkBoxTree.expandRow(i);
    }
    scroll.setViewportView(checkBoxTree);

    add(scroll, java.awt.BorderLayout.CENTER);

    actPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(options.getMsg("edit_act_copy_dest")));
    actPanel.setLayout(new java.awt.GridBagLayout());

    actScroll.setPreferredSize(new java.awt.Dimension(200, 300));

    actList.setModel(abe.getListModel());
    actScroll.setViewportView(actList);

    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    actPanel.add(actScroll, gridBagConstraints);

    selectAllBtn.setText(options.getMsg("SELECT_ALL"));
    selectAllBtn.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        selectAllBtnActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    actPanel.add(selectAllBtn, gridBagConstraints);

    selectNoneBtn.setText(options.getMsg("SELECT_NONE"));
    selectNoneBtn.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        selectNoneBtnActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    actPanel.add(selectNoneBtn, gridBagConstraints);

    add(actPanel, java.awt.BorderLayout.EAST);
  } // </editor-fold>//GEN-END:initComponents

  private void selectNoneBtnActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_selectNoneBtnActionPerformed

    actList.clearSelection();
  } // GEN-LAST:event_selectNoneBtnActionPerformed

  private void selectAllBtnActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_selectAllBtnActionPerformed

    actList.setSelectionInterval(0, actList.getModel().getSize() - 1);
  } // GEN-LAST:event_selectAllBtnActionPerformed

  public boolean showDialog(java.awt.Component parent) {
    boolean result = false;

    if (options.getMessages().showInputDlg(parent, this, "edit_act_copy_title")) {
      final Object[] selectedItems = actList.getSelectedValues();
      if (selectedItems == null || selectedItems.length == 0) {
        options.getMessages().showAlert(this, "edit_act_copy_err_noSelection");
      } else {
        final ActivityEditor srcActEd = abed.getActivityEditor();
        srcActEd.collectData();
        final Activity srcAct = srcActEd.getActivity();
        final ProgressDialog pd = new ProgressDialog(this, options);
        edu.xtec.util.SwingWorker sw = new edu.xtec.util.SwingWorker() {

          @Override
          public Object construct() {
            int modifiedItems = 0;
            for (int i = 0; i < selectedItems.length; i++) {
              ActivityBagElementEditor targetEd = (ActivityBagElementEditor) selectedItems[i];
              if (targetEd != abed) {
                ActivityEditor targetActEd = targetEd.getActivityEditor();
                Activity targetAct = targetActEd.getActivity();
                pd.setFileLabel(targetAct.name);
                copyAttributes(srcAct, targetAct);
                pd.setProgressValue(modifiedItems++);
                targetActEd.setModified(true);
                targetEd.forgetActivityEditor();
              }
              if (isCancelled() || Thread.currentThread().isInterrupted())
                break;
            }
            return new Integer(modifiedItems);
          }

          @Override
          public void finished() {
            pd.setVisible(false);
          }
        };
        pd.setProgressMax(selectedItems.length);
        pd.start("WORKING", "edit_act_copy_action_prefix", sw, true, true, false);
      }
    }
    return result;
  }

  private CheckBoxTreeObject bgColor, bgGradient, bgImage, activityBgColor, activityBgGradient, transparentBg, border,
      position, margin, msgPrev, msgIni, msgEnd, msgErr, repInclude, repActions, skin, evSounds, cTime, maxTime, cTries,
      maxTries, cScore, scramble, helpBtn, infoBtn, gridA, gridB, textGrid, textFontFace, textFontSize, textStyle,
      textColour, targetColour, errorColour, tabSpace;

  private TreeModel getTreeModel() {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(options.getMsg("edit_act_copy_attributes"));

    // Main Window
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(options.getMsg("edit_act_copy_style_main"));
    node.add(bgColor = new CheckBoxTreeObject(options.getMsg("edit_act_copy_bgColor"), true));
    node.add(bgGradient = new CheckBoxTreeObject(options.getMsg("edit_act_copy_gradient"), true));
    node.add(bgImage = new CheckBoxTreeObject(options.getMsg("edit_act_copy_bgImage"), true));
    root.add(node);

    // Play Window
    node = new DefaultMutableTreeNode(options.getMsg("edit_act_copy_style_play"));
    node.add(activityBgColor = new CheckBoxTreeObject(options.getMsg("edit_act_copy_bgColor"), true));
    node.add(activityBgGradient = new CheckBoxTreeObject(options.getMsg("edit_act_copy_gradient"), true));
    node.add(transparentBg = new CheckBoxTreeObject(options.getMsg("edit_act_copy_transparentBg"), true));
    node.add(border = new CheckBoxTreeObject(options.getMsg("edit_act_copy_border"), true));
    node.add(margin = new CheckBoxTreeObject(options.getMsg("edit_act_copy_margin"), true));
    node.add(position = new CheckBoxTreeObject(options.getMsg("edit_act_copy_position"), false));
    root.add(node);

    // Messages
    node = new DefaultMutableTreeNode(options.getMsg("edit_act_copy_messages"));
    node.add(msgPrev = new CheckBoxTreeObject(options.getMsg("edit_act_copy_messages_prev"), true));
    node.add(msgIni = new CheckBoxTreeObject(options.getMsg("edit_act_copy_messages_ini"), true));
    node.add(msgEnd = new CheckBoxTreeObject(options.getMsg("edit_act_copy_messages_end"), true));
    node.add(msgErr = new CheckBoxTreeObject(options.getMsg("edit_act_copy_messages_err"), true));
    root.add(node);

    // Reports
    node = new DefaultMutableTreeNode(options.getMsg("edit_act_copy_reports"));
    node.add(repInclude = new CheckBoxTreeObject(options.getMsg("edit_act_copy_rep_include"), false));
    node.add(repActions = new CheckBoxTreeObject(options.getMsg("edit_act_copy_rep_actions"), false));
    root.add(node);

    // Interface
    node = new DefaultMutableTreeNode(options.getMsg("edit_act_copy_interface"));
    node.add(skin = new CheckBoxTreeObject(options.getMsg("edit_act_copy_skin"), false));
    node.add(evSounds = new CheckBoxTreeObject(options.getMsg("edit_act_copy_evSounds"), false));
    root.add(node);

    // Counters
    node = new DefaultMutableTreeNode(options.getMsg("edit_act_copy_counters"));
    node.add(cTime = new CheckBoxTreeObject(options.getMsg("edit_act_copy_cTime"), true));
    node.add(maxTime = new CheckBoxTreeObject(options.getMsg("edit_act_copy_maxTime"), false));
    node.add(cTries = new CheckBoxTreeObject(options.getMsg("edit_act_copy_cTries"), true));
    node.add(maxTries = new CheckBoxTreeObject(options.getMsg("edit_act_copy_maxTries"), false));
    node.add(cScore = new CheckBoxTreeObject(options.getMsg("edit_act_copy_cScore"), true));
    node.add(scramble = new CheckBoxTreeObject(options.getMsg("edit_act_copy_scramble"), false));
    root.add(node);

    // Buttons
    node = new DefaultMutableTreeNode(options.getMsg("edit_act_copy_buttons"));
    node.add(helpBtn = new CheckBoxTreeObject(options.getMsg("edit_act_copy_btnHelp"), false));
    node.add(infoBtn = new CheckBoxTreeObject(options.getMsg("edit_act_copy_btnInfo"), false));
    root.add(node);

    // Grids
    node = new DefaultMutableTreeNode(options.getMsg("edit_act_copy_grids"));
    node.add(gridA = new CheckBoxTreeObject(options.getMsg("edit_act_copy_gridA"), true));
    node.add(gridB = new CheckBoxTreeObject(options.getMsg("edit_act_copy_gridB"), true));
    node.add(textGrid = new CheckBoxTreeObject(options.getMsg("edit_act_copy_textGrid"), true));
    root.add(node);

    // Text
    node = new DefaultMutableTreeNode(options.getMsg("edit_act_copy_text"));
    node.add(textFontFace = new CheckBoxTreeObject(options.getMsg("edit_act_copy_fontFace"), true));
    node.add(textFontSize = new CheckBoxTreeObject(options.getMsg("edit_act_copy_fontSize"), true));
    node.add(textStyle = new CheckBoxTreeObject(options.getMsg("edit_act_copy_fontStyle"), true));
    node.add(textColour = new CheckBoxTreeObject(options.getMsg("edit_act_copy_textColour"), true));
    node.add(targetColour = new CheckBoxTreeObject(options.getMsg("edit_act_copy_textTargetColour"), true));
    node.add(errorColour = new CheckBoxTreeObject(options.getMsg("edit_act_copy_textErrorColour"), true));
    node.add(tabSpace = new CheckBoxTreeObject(options.getMsg("edit_act_copy_tabSpace"), false));
    root.add(node);

    return new DefaultTreeModel(root);
  }

  private void copyAttributes(Activity srcAct, Activity targetAct) {

    // Main window
    if (bgColor.isSelected())
      targetAct.bgColor = srcAct.bgColor;
    if (bgGradient.isSelected())
      targetAct.bgGradient = srcAct.bgGradient;
    if (bgImage.isSelected()) {
      targetAct.bgImageFile = srcAct.bgImageFile;
      targetAct.tiledBgImg = srcAct.tiledBgImg;
    }
    if (margin.isSelected())
      targetAct.margin = srcAct.margin;

    // Play window
    if (activityBgColor.isSelected())
      targetAct.activityBgColor = srcAct.activityBgColor;
    if (activityBgGradient.isSelected())
      targetAct.activityBgGradient = srcAct.activityBgGradient;
    if (transparentBg.isSelected())
      targetAct.transparentBg = srcAct.transparentBg;
    if (border.isSelected())
      targetAct.border = srcAct.border;
    if (position.isSelected()) {
      targetAct.absolutePositioned = srcAct.absolutePositioned;
      targetAct.absolutePosition = srcAct.absolutePosition;
    }

    // messages
    if (msgPrev.isSelected() && srcAct.messages[Activity.PREVIOUS] != null
        && targetAct.messages[Activity.PREVIOUS] != null)
      srcAct.messages[Activity.PREVIOUS].copyStyleTo(targetAct.messages[Activity.PREVIOUS]);
    if (msgIni.isSelected() && srcAct.messages[Activity.MAIN] != null && targetAct.messages[Activity.MAIN] != null)
      srcAct.messages[Activity.MAIN].copyStyleTo(targetAct.messages[Activity.MAIN]);
    if (msgEnd.isSelected() && srcAct.messages[Activity.END] != null && targetAct.messages[Activity.END] != null)
      srcAct.messages[Activity.END].copyStyleTo(targetAct.messages[Activity.END]);
    if (msgErr.isSelected() && srcAct.messages[Activity.END_ERROR] != null
        && targetAct.messages[Activity.END_ERROR] != null)
      srcAct.messages[Activity.END_ERROR].copyStyleTo(targetAct.messages[Activity.END_ERROR]);

    // reports
    if (repInclude.isSelected())
      targetAct.includeInReports = srcAct.includeInReports;
    if (repActions.isSelected())
      targetAct.reportActions = srcAct.reportActions;

    // interface
    if (skin.isSelected())
      targetAct.skinFileName = srcAct.skinFileName;
    if (evSounds.isSelected())
      targetAct.eventSounds = srcAct.eventSounds;

    // counters
    if (cTime.isSelected())
      targetAct.bTimeCounter = srcAct.bTimeCounter;
    if (maxTime.isSelected()) {
      targetAct.maxTime = srcAct.maxTime;
      targetAct.countDownTime = srcAct.countDownTime;
    }
    if (cTries.isSelected())
      targetAct.bActionsCounter = srcAct.bActionsCounter;
    if (maxTries.isSelected()) {
      targetAct.maxActions = srcAct.maxActions;
      targetAct.countDownActions = srcAct.countDownActions;
    }
    if (cScore.isSelected())
      targetAct.bScoreCounter = srcAct.bScoreCounter;
    if (scramble.isSelected())
      targetAct.shuffles = srcAct.shuffles;

    // Buttons
    if (helpBtn.isSelected()) {
      targetAct.helpWindow = srcAct.helpWindow;
      targetAct.showSolution = srcAct.showSolution;
    }
    if (infoBtn.isSelected()) {
      targetAct.infoUrl = srcAct.infoUrl;
      targetAct.infoCmd = srcAct.infoCmd;
    }

    // Grids
    if (gridA.isSelected() && srcAct.abc != null && srcAct.abc.length > 0 && srcAct.abc[0] != null
        && targetAct.abc != null && targetAct.abc.length > 0 && targetAct.abc[0] != null)
      srcAct.abc[0].copyStyleTo(targetAct.abc[0]);
    if (gridB.isSelected() && srcAct.abc != null && srcAct.abc.length > 1 && srcAct.abc[1] != null
        && targetAct.abc != null && targetAct.abc.length > 1 && targetAct.abc[1] != null)
      srcAct.abc[1].copyStyleTo(targetAct.abc[1]);
    if (textGrid.isSelected() && srcAct.tgc != null && targetAct.tgc != null)
      srcAct.tgc.copyStyleTo(targetAct.tgc);

    if (srcAct instanceof TextActivityBase && targetAct instanceof TextActivityBase) {
      TextActivityBase txSrcAct = (TextActivityBase) srcAct;
      TextActivityBase txTargetAct = (TextActivityBase) targetAct;

      if (textFontFace.isSelected() || textFontSize.isSelected() || textStyle.isSelected() || textColour.isSelected()
          || targetColour.isSelected() || errorColour.isSelected() || tabSpace.isSelected()) {
        StyleContext sc = TextActivityDocument.copyStylesFrom(txSrcAct.getStyleContext(), txTargetAct.getStyleContext(),
            textFontFace.isSelected(), textFontSize.isSelected(), textStyle.isSelected(), textColour.isSelected(),
            targetColour.isSelected(), errorColour.isSelected());
        if (sc != null) {
          txTargetAct.setStyleContext(sc);
        }
        if (tabSpace.isSelected())
          txTargetAct.getDocument().setTabSpc(txSrcAct.getDocument().getTabSpc());
      }
    }
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JList<Object> actList;
  private edu.xtec.jclic.beans.CheckBoxTree checkBoxTree;
  private javax.swing.JButton selectAllBtn;
  private javax.swing.JButton selectNoneBtn;
  // End of variables declaration//GEN-END:variables

}
