/*
 * File    : ExportToJSDlg.java
 * Created : 23-nov-2015 16:37
 * 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.project;

import edu.xtec.util.Messages;
import edu.xtec.util.Options;
import edu.xtec.util.ResourceBridge;
import edu.xtec.util.StrUtils;
import java.awt.Component;
import java.io.File;
import javax.swing.JFileChooser;

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

  ResourceBridge rb;
  Options options;
  String outputFolder;
  String scormFile;
  boolean exportAll = true;
  boolean exportScorm = true;

  /** Creates new form ExportToJSDlg */
  public ExportToJSDlg(ResourceBridge rb) {
    this.rb = rb;
    options = rb.getOptions();
    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;

    exportPanel = new javax.swing.JPanel();
    exportLb = new javax.swing.JLabel();
    outputFolderLb = new javax.swing.JLabel();
    outputFolderText = new javax.swing.JTextField();
    outputFolderBtn = new javax.swing.JButton();
    javax.swing.JLabel spacer2 = new javax.swing.JLabel();
    allPrjChk = new javax.swing.JCheckBox();
    spacer = new javax.swing.JLabel();
    scormPanel = new javax.swing.JPanel();
    exportScormChk = new javax.swing.JCheckBox();
    scormFolderLb = new javax.swing.JLabel();
    scormFileText = new javax.swing.JTextField();
    scormFileBtn = new javax.swing.JButton();
    javax.swing.JLabel spacer3 = new javax.swing.JLabel();

    setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
    setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.Y_AXIS));

    exportPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("HTML5"));
    exportPanel.setLayout(new java.awt.GridBagLayout());

    exportLb.setText(options.getMsg("export_project_desc"));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
    gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
    exportPanel.add(exportLb, gridBagConstraints);

    outputFolderLb.setLabelFor(outputFolderText);
    outputFolderLb.setText(options.getMsg("export_project_output_folder"));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
    gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
    exportPanel.add(outputFolderLb, gridBagConstraints);

    outputFolderText.setToolTipText(options.getMsg("edit_new_project_folder_tooltip"));
    outputFolderText.setMinimumSize(new java.awt.Dimension(320, 21));
    outputFolderText.setPreferredSize(new java.awt.Dimension(320, 21));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
    exportPanel.add(outputFolderText, gridBagConstraints);

    outputFolderBtn.setText(options.getMsg("edit_new_project_folder_browse"));
    outputFolderBtn.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        outputFolderBtnActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
    gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
    exportPanel.add(outputFolderBtn, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.weightx = 1.0;
    exportPanel.add(spacer2, gridBagConstraints);

    allPrjChk.setText(options.getMsg("export_project_includeAll"));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
    exportPanel.add(allPrjChk, gridBagConstraints);

    add(exportPanel);

    spacer.setPreferredSize(new java.awt.Dimension(25, 25));
    add(spacer);

    scormPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("SCORM"));
    scormPanel.setLayout(new java.awt.GridBagLayout());

    exportScormChk.setText(options.getMsg("export_project_exportSCORM"));
    exportScormChk.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        scormSelChanged(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
    scormPanel.add(exportScormChk, gridBagConstraints);

    scormFolderLb.setLabelFor(scormFileText);
    scormFolderLb.setText(options.getMsg("export_project_scorm_file"));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
    gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
    scormPanel.add(scormFolderLb, gridBagConstraints);

    scormFileText.setToolTipText(options.getMsg("export_project_scorm_file_tooltip"));
    scormFileText.setMinimumSize(new java.awt.Dimension(320, 21));
    scormFileText.setPreferredSize(new java.awt.Dimension(320, 21));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
    scormPanel.add(scormFileText, gridBagConstraints);

    scormFileBtn.setText(options.getMsg("export_project_scorm_file_browse"));
    scormFileBtn.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        scormFileBtnActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
    gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
    scormPanel.add(scormFileBtn, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.weightx = 1.0;
    scormPanel.add(spacer3, gridBagConstraints);

    add(scormPanel);
  } // </editor-fold>//GEN-END:initComponents

  private JFileChooser chooser;
  private JFileChooser scormFileChooser;

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

    if (chooser == null) {
      chooser = new JFileChooser();
      chooser.setApproveButtonText(options.getMsg("export_project_selectFolder"));
      chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    }

    outputFolder = StrUtils.nullableString(outputFolderText.getText());
    if (outputFolder != null) {
      try {
        File f = new File(outputFolder);
        if (!f.exists()) {
          f.mkdirs();
        }
        chooser.setSelectedFile(f);
      } catch (Exception ex) {
        // Unable to create folders. By now, do nothing
      }
    }

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
      outputFolder = chooser.getSelectedFile().getAbsolutePath();
      outputFolderText.setText(outputFolder);
    }
  } // GEN-LAST:event_outputFolderBtnActionPerformed

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

    if (scormFileChooser == null) {
      scormFileChooser = new JFileChooser();
      scormFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    }

    scormFile = StrUtils.nullableString(scormFileText.getText());
    if (scormFile != null) {
      try {
        File f = new File(scormFile);
        if (!f.getParentFile().exists()) {
          f.getParentFile().mkdirs();
        }
        scormFileChooser.setSelectedFile(f);
      } catch (Exception ex) {
        // Unable to create folders. By now, do nothing
      }
    }

    if (scormFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
      scormFile = scormFileChooser.getSelectedFile().getAbsolutePath();
      scormFileText.setText(scormFile);
    }
  } // GEN-LAST:event_scormFileBtnActionPerformed

  private void scormSelChanged(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_scormSelChanged
    scormFileBtn.setEnabled(exportScormChk.isSelected());
    scormFolderLb.setEnabled(exportScormChk.isSelected());
  } // GEN-LAST:event_scormSelChanged

  public void fillData() {
    outputFolderText.setText(outputFolder == null ? "" : outputFolder);
    scormFileText.setText(scormFile == null ? "" : scormFile);
    allPrjChk.setSelected(exportAll);
    exportScormChk.setSelected(exportScorm);
  }

  public void getData() {
    outputFolder = StrUtils.nullableString(outputFolderText.getText());
    exportAll = allPrjChk.isSelected();
    exportScorm = exportScormChk.isSelected();
    scormFile = StrUtils.nullableString(scormFileText.getText());
  }

  public static String[] prompt(ResourceBridge rb, Component parent, String inputPath, String exportBasePath,
      String scormBasePath) {
    String[] result = null;
    ExportToJSDlg exportDlg = new ExportToJSDlg(rb);
    Messages msg = rb.getOptions().getMessages();
    File inputFile = new File(inputPath);
    String inputBase = inputFile.getName();
    exportDlg.exportAll = !inputBase.toLowerCase().equals("projects");
    exportDlg.outputFolder = (new File(new File(exportBasePath), inputBase)).getPath();
    exportDlg.scormFile = (new File(new File(scormBasePath), inputBase + ".scorm.zip")).getPath();
    exportDlg.fillData();
    while (result == null) {
      if (!msg.showInputDlg(parent, exportDlg, "export_project_title")) {
        break;
      }
      exportDlg.getData();
      if (exportDlg.outputFolder == null) {
        msg.showErrorWarning(parent, "export_project_err_empty", null);
      } else {
        try {
          boolean folderOk = true;
          boolean scormOk = true;

          File outputFolderFile = new File(exportDlg.outputFolder);

          if (exportDlg.outputFolder.equals(inputPath)) {
            msg.showErrorWarning(parent, "export_project_err_sameFolder", null);
            folderOk = false;
          } else if (exportDlg.outputFolder.startsWith(inputPath)) {
            msg.showErrorWarning(parent, "export_project_err_nestedFolders", null);
            folderOk = false;
          } else if (outputFolderFile.exists() && outputFolderFile.isDirectory()) {
            if (outputFolderFile.list().length > 0) {
              folderOk = msg.showQuestionDlg(parent, "export_project_warning_noEmptyFolder", null,
                  "yn") == Messages.YES;
            }
          } else if (!outputFolderFile.mkdirs()) {
            msg.showErrorWarning(parent, "edit_new_project_err_folderCreation", null);
            folderOk = false;
          }

          if (folderOk && exportDlg.exportScorm) {
            if (exportDlg.scormFile == null) {
              msg.showErrorWarning(parent, "export_project_scorm_file_err_empty", null);
              scormOk = false;
            } else {
              File scormFile = new File(exportDlg.scormFile);
              if (scormFile.exists()) {
                scormOk = msg.showQuestionDlg(parent, "export_project_scorm_file_exists", null, "yn") == Messages.YES;
              } else if (!scormFile.getParentFile().exists() && !scormFile.getParentFile().mkdirs()) {
                msg.showErrorWarning(parent, "edit_new_project_err_folderCreation", null);
                scormOk = false;
              }
            }
          }

          if (folderOk && scormOk) {
            result = new String[] { exportDlg.outputFolder, inputPath, exportDlg.exportAll ? "true" : "false",
                exportDlg.exportScorm ? exportDlg.scormFile : null };
          }
        } catch (Exception ex) {
          msg.showErrorWarning(parent, "ERROR", ex);
        }
      }
    }
    return result;
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JCheckBox allPrjChk;
  private javax.swing.JLabel exportLb;
  private javax.swing.JPanel exportPanel;
  private javax.swing.JCheckBox exportScormChk;
  private javax.swing.JButton outputFolderBtn;
  private javax.swing.JLabel outputFolderLb;
  private javax.swing.JTextField outputFolderText;
  private javax.swing.JButton scormFileBtn;
  private javax.swing.JTextField scormFileText;
  private javax.swing.JLabel scormFolderLb;
  private javax.swing.JPanel scormPanel;
  private javax.swing.JLabel spacer;
  // End of variables declaration//GEN-END:variables

}
