/*
 * File    : SelectActivityClass.java
 * Created : 09-aug-2004 11: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.bags;

import edu.xtec.jclic.ActivityEditor;
import edu.xtec.util.Options;
import edu.xtec.util.StrUtils;
import edu.xtec.util.TripleString;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

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

  Options options;
  private List<TripleString> activityClasses;
  private List<TripleString> currentSet;
  private String currentClassName;

  /** Creates new form SelectActivityClass */
  public SelectActivityClass(Options options) {
    this.options = options;
    activityClasses = ActivityEditor.getSystemActivityList(options);
    currentSet = new ArrayList<TripleString>();
    initComponents();
    classList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent e) {
        if (!e.getValueIsAdjusting()) {
          updateSelection();
        }
      }
    });
    setListFilter(null, true);
  }

  /**
   * 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;

    jSplitPane1 = new javax.swing.JSplitPane();
    javax.swing.JScrollPane scroll = new javax.swing.JScrollPane();
    classList = new javax.swing.JList<>();
    javax.swing.JPanel rightPanel = new javax.swing.JPanel();
    scroll2 = new javax.swing.JScrollPane();
    descText = new javax.swing.JEditorPane();
    promptPanel = new javax.swing.JPanel();
    javax.swing.JLabel classLb = new javax.swing.JLabel();
    classField = new javax.swing.JTextField();

    setMinimumSize(new java.awt.Dimension(400, 300));
    setPreferredSize(new java.awt.Dimension(500, 300));
    setLayout(new java.awt.BorderLayout());

    scroll.setMinimumSize(new java.awt.Dimension(100, 200));

    classList.setMinimumSize(new java.awt.Dimension(200, 0));
    scroll.setViewportView(classList);

    jSplitPane1.setLeftComponent(scroll);

    rightPanel.setLayout(new java.awt.GridBagLayout());

    scroll2.setMinimumSize(new java.awt.Dimension(200, 200));

    descText.setEditable(false);
    descText.setContentType("text/html"); // NOI18N
    scroll2.setViewportView(descText);

    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
    rightPanel.add(scroll2, gridBagConstraints);

    promptPanel.setLayout(new java.awt.GridBagLayout());

    classLb.setText(options.getMsg("edit_act_newActivity_class"));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
    gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
    promptPanel.add(classLb, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
    promptPanel.add(classField, gridBagConstraints);

    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
    gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
    rightPanel.add(promptPanel, gridBagConstraints);

    jSplitPane1.setRightComponent(rightPanel);

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

  @SuppressWarnings("unchecked")
  public final void setListFilter(String[] allowedClasses, boolean allowOther) {
    List<TripleString> v = new ArrayList<TripleString>();
    if (allowedClasses != null) {
      for (int i = 0; i < allowedClasses.length; i++) {
        int p = TripleString.getFirstItemWithClass(activityClasses, allowedClasses[i]);
        if (p >= 0)
          v.add(activityClasses.get(p));
      }
    } else {
      v.addAll(activityClasses);
    }
    if (allowOther) {
      v.add(new TripleString(options.getMsg("edit_act_newActivity_other"), null, null));
    }
    classList.setListData(v.toArray());
    currentSet = v;
    setCurrentClassName(currentClassName);
  }

  private void updateSelection() {
    Object o = classList.getSelectedValue();
    boolean showPrompt = false;
    if (o instanceof TripleString) {
      TripleString ts = (TripleString) o;
      currentClassName = ts.getClassName();
      descText.setContentType("text/html");
      descText.setText(getFormattedHtmlText(ts.toString(), ts.getDescription(), ts.getClassName()));
    } else if (o != null) {
      showPrompt = true;
      currentClassName = StrUtils.nullableString(classField.getText());
      descText.setContentType("text/html");
      descText.setText(getFormattedHtmlText(o.toString(), options.getMsg("edit_act_newActivity_info"), null));
    } else {
      currentClassName = null;
      descText.setContentType("text/html");
      descText.setText("");
    }
    promptPanel.setVisible(showPrompt);
    if (classList.getSelectedIndex() >= 0) {
      SwingUtilities.invokeLater(new Runnable() {
        public void run() {
          classList.ensureIndexIsVisible(classList.getSelectedIndex());
        }
      });
    }
  }

  private static final String TYPE_STYLE = "font-family:Helvetica;font-size:12;font-weight:bold;";
  private static final String DESC_STYLE = "font-family:Helvetica;font-size:12;";

  String getFormattedHtmlText(String type, String desc, String className) {
    StringBuilder sb = new StringBuilder();
    sb.append("<html><body>");
    if (type != null) {
      sb.append("<p style=\"").append(TYPE_STYLE).append("\">").append(type).append("</p>");
    }
    if (desc != null) {
      sb.append("<p style=\"").append(DESC_STYLE).append("\">").append(desc).append("</p>");
    }
    if (className != null) {
      sb.append("<p style=\"").append(DESC_STYLE).append("\">");
      sb.append(options.getMsg("edit_act_newActivity_class")).append(" <i>").append(className);
      sb.append("</i></p>");
    }
    sb.append("</body></html>");
    return sb.substring(0);
  }

  /**
   * Getter for property currentClassName.
   *
   * @return Value of property currentClassName.
   */
  public java.lang.String getCurrentClassName() {
    updateSelection();
    return StrUtils.nullableString(currentClassName);
  }

  /**
   * Setter for property currentClassName.
   *
   * @param currentClassName New value of property currentClassName.
   */
  public void setCurrentClassName(java.lang.String currentClassName) {
    this.currentClassName = currentClassName;
    if (currentClassName != null) {
      int p = TripleString.getFirstItemWithClass(currentSet, currentClassName);
      if (p >= 0)
        classList.setSelectedIndex(p);
      else
        classField.setText(StrUtils.secureString(currentClassName));
    }
    updateSelection();
  }

  private JLabel alertLabel;

  public void setAlertMsg(String alertMsg) {
    if (alertLabel != null)
      remove(alertLabel);
    alertLabel = new JLabel(alertMsg);
    add(alertLabel, BorderLayout.NORTH);
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  protected javax.swing.JTextField classField;
  private javax.swing.JList classList;
  private javax.swing.JEditorPane descText;
  private javax.swing.JSplitPane jSplitPane1;
  private javax.swing.JPanel promptPanel;
  private javax.swing.JScrollPane scroll2;
  // End of variables declaration//GEN-END:variables

}
