/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/08/12, 15:27
!  AUTHOR(S): KOGA, Junichiro
!  File : IntroPanel.java
!  
!  Contact address :  Phase System Consortium
!                     E-mail: phase_system@nims.go.jp URL https://azuma.nims.go.jp
!
!
!   Since 2002, this program set had been intensively developed as a part of the following 
!  national projects supported by the Ministry of Education, Culture, Sports, Science and
!  Technology (MEXT) of Japan; "Frontier Simulation Software for Industrial Science
!  (FSIS)" from 2002 to 2005, "Revolutionary Simulation Software (RSS21)" from 2006 to
!  2008. "Research and Development of Innovative Simulation Software (RISS)" from 2008
!  to 2013. These projects is lead by the Center for Research on Innovative Simulation 
!  Software (CISS), the Institute of Industrial Science (IIS), the University of Tokyo.
!   Since 2013, this program set has been further developed centering on PHASE System
!  Consortium. 
!   The activity of development of this program set has been supervised by Takahisa Ohno.
!
!=======================================================================
 */

package ciss.phase_viewer.plugins.projectmanipulator;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.TitledBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import org.apache.log4j.Logger;
import org.jdom.Element;

import ciss.phase_viewer.common.ChaseFileChooser;
import ciss.phase_viewer.inputinterface.DataManager;
import ciss.phase_viewer.inputinterface.InputInterface;
import ciss.phase_viewer.jdom.MyElement;
import ciss.phase_viewer.plugins.projectmanipulator.phase.PhaseConstants;
import ciss.phase_viewer.projectbrowser.ProjectBrowserUtils;
import ciss.phase_viewer.projectbrowser.ProjectInfo;
import ciss.phase_viewer.projectbrowser.ProjectManipulator;
import ciss.phase_viewer.settings.GlobalProperties;
import ciss.phase_viewer.settings.PropertiesManager;

/**
 * 「プロジェクト制御画面」でまず一番はじめに表示されることを想定したGUI.
 * 
 * @author
 */
public class IntroPanel extends ProjectManipulator {
    /**
	 * 
	 */
    private static final long serialVersionUID = -5004359985536437617L;

    private Logger logger = Logger.getLogger(IntroPanel.class.getName());

    private Dimension labelSize = new Dimension(500, 40);

    private JTextArea comment;

    /**
     * Creates new form IntroPanel
     * 
     * @param projectInfo
     *            このプロジェクトの情報を格納したオブジェクト
     */
    public IntroPanel(ProjectInfo projectInfo) {
        super(projectInfo);
    }

    /**
     * Creates new form IntroPanel
     * 
     * @param projectInfo
     *            このプロジェクトの情報を格納したオブジェクト
     * @param url
     *            プロジェクトの説明書きのあるhtmlファイルのURL
     */
    // public IntroPanel(ProjectInfo projectInfo,URL url) {
    // super(projectInfo);
    // setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
    // customComponents();
    // initComponents();
    // ProjectBrowserUtils.setHtmlToEditorPane(jEditorPane1,url);
    // }
    private JLabel parentPath;

    private void customComponents() {
        JPanel p = new JPanel();
        p.setBorder(new TitledBorder("project information"));
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));

        JPanel plabel = new JPanel();
        String parentDir = projectInfo.getParentDir();
        plabel.setLayout(new GridLayout(3, 1));

        JLabel date = new JLabel(projectInfo.getDate());
        date.setPreferredSize(labelSize);
        date.setBorder(new TitledBorder("date of creation"));
        plabel.add(date);

        // JLabel type = new JLabel(projectInfo.getProjectType());
        // type.setPreferredSize(labelSize);
        // type.setBorder(new TitledBorder("project type"));
        // p.add(type);

        JLabel name = new JLabel(projectInfo.getProjectName());
        name.setPreferredSize(labelSize);
        name.setBorder(new TitledBorder("project name"));
        plabel.add(name);

        JPanel panelPath = new JPanel();
        JLabel path = new JLabel(projectInfo.getProjectDirectory());
        path.setToolTipText(projectInfo.getProjectDirectory());
        path.setPreferredSize(labelSize);
        path.setBorder(new TitledBorder("base directory"));
        panelPath.add(path);
        if (parentDir != null) {
            panelPath.setLayout(new GridLayout(1, 2));
            parentPath = new JLabel(parentDir);
            // parentPath.setBorder(new TitledBorder("parent directory"));
            parentPath.setToolTipText(parentDir);
            JPanel parentPanel = new JPanel();
            parentPanel.setLayout(new BorderLayout());
            parentPanel.setBorder(new TitledBorder("parent directory"));
            parentPanel.add(parentPath, BorderLayout.WEST);
            JButton btnchange = new JButton("select new parent");
            parentPanel.add(btnchange, BorderLayout.EAST);
            panelPath.add(parentPanel);
            btnchange.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    bootParentChanger();
                }
            });
        } else {
            panelPath.setLayout(new GridLayout(1, 1));
        }
        plabel.add(panelPath);

        JPanel pcomment = new JPanel();
        pcomment.setLayout(new GridLayout());
        pcomment.setBorder(new TitledBorder("comments"));
        comment = new JTextArea(1, 20);
        comment.setDragEnabled(true);
        comment.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent ce) {
                postProcess();
            }
        });

        JScrollPane scr = new JScrollPane();
        scr.getViewport().setView(comment);
        pcomment.add(scr);

        p.add(plabel);
        p.add(pcomment);
        add(p);
    }

    private void bootParentChanger() {
        ChaseFileChooser fdlg = new ChaseFileChooser(true);
        fdlg.setDialogType(JFileChooser.CUSTOM_DIALOG);
        fdlg.setDialogTitle("Open");
        fdlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        if (fdlg.showDialog(this, "open") != JFileChooser.APPROVE_OPTION) {
            return;
        }

        String newParentDir = fdlg.getSelectedFile().getAbsolutePath();
        updateParent(newParentDir);
    }

    protected void updateParent(String newParentDir) {
    }

    public boolean postProcess() {
        String scomm = MyElement.encode(comment.getText());
        Element projElement = projectInfo.getProjectElement();
        Element comm = projElement.getChild("comment");
        if (comm == null) {
            comm = new Element("comment");
            comm.setText(scomm);
            projElement.addContent(comm);
        } else {
            comm.setText(scomm);
        }
        logger.debug("post process...");
        // Document doc = projectInfo.getProjectPropertyDocument();
        // if ( doc == null ) {
        // return true;
        // }
        //
        // Element root = doc.getRootElement();
        // if ( root == null ) {
        // return true;
        // }
        // Element elem = root.getChild("comment");
        //
        // if ( elem != null ) {
        // elem.setText(scomm);
        // } else {
        // elem = new Element("comment");
        // elem.setText(scomm);
        // root.setContent(elem);
        // }
        //
        // projectInfo.saveProjectPropertyDocument();

        return true;
    }

    public void recreate() {
        if (parentPath != null) {
            parentPath.setText(projectInfo.getParentDir());
            parentPath.setToolTipText(projectInfo.getParentDir());
        }
    }

    public void init() {

        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        customComponents();
        initComponents();

        URL url = projectInfo.getProjectDescriptionURL();
        if (url != null) {
            ProjectBrowserUtils.setHtmlToEditorPane(jEditorPane1, url);
        }
        Element projElement = projectInfo.getProjectElement();
        String comm = MyElement.decode(projElement.getChildTextTrim("comment"));
        if (comm != null && comm.length() != 0) {
            comment.setText(comm);
        }

        String nfinp = projectInfo.getProjectDirectory()
                + System.getProperty("file.separator")
                + projectInfo.getChaseFileManager().getFile("F_INP")
                        .getFileName();
        logger.debug("nfinp: " + nfinp);
        java.net.URL urlspec = PhaseConstants.TABLESPEC;
        GlobalProperties gp = PropertiesManager
                .getGlobalProperties(PropertiesManager.PROPERTIES_PVIEWER);
        boolean obs = new Boolean(
                gp.getProperty("phaseinput_monitor_external_edit"))
                .booleanValue();
        DataManager dm = new DataManager(nfinp, urlspec, obs);
        dm.parse();
        InputInterface inputInterface = dm.getInputInterface();
        projectInfo.setInputInterface(inputInterface);
        projectInfo.setInputDataManager(dm);
        /* 「擬ポテンシャル」エントリーをむりやり作る */
        logger.debug("creating elempanel...");
        logger.debug("projdir now: " + projectInfo.getProjectDirectory());
        // ElemPanel ele = new ElemPanel(projectInfo);
        // projectInfo.registerGUI(ele);
        // ele.setSilent(true);

        // get comments

        // Document doc = projectInfo.getProjectPropertyDocument();
        // if ( doc != null ) {
        // Element element = doc.getRootElement();
        // String comm = MyElement.decode(element.getChildTextTrim("comment"));
        // if ( comm != null && comm.length() != 0 ) {
        // comment.setText(comm);
        // }
        // }
    }

    public void initializeProject() {
    }

    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jEditorPane1 = new javax.swing.JEditorPane();

        setLayout(new java.awt.GridLayout(2, 0));

        setBorder(new javax.swing.border.TitledBorder(null, "Welcome to "
                + projectInfo.getProjectType() + "!",
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                javax.swing.border.TitledBorder.DEFAULT_POSITION,
                new java.awt.Font("MS Sans Serif", 0, 11), new java.awt.Color(
                        0, 0, 153)));
        jPanel1.setLayout(new java.awt.GridLayout());

        jPanel1.setBorder(new javax.swing.border.TitledBorder(null,
                "description",
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                javax.swing.border.TitledBorder.DEFAULT_POSITION,
                new java.awt.Font("MS Sans Serif", 1, 12)));
        jScrollPane1
                .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane1.setViewportView(jEditorPane1);

        jPanel1.add(jScrollPane1);

        add(jPanel1);

    }

    private javax.swing.JEditorPane jEditorPane1;

    private javax.swing.JPanel jPanel1;

    private javax.swing.JScrollPane jScrollPane1;

}
