/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/11/11, 20:50
!  AUTHOR(S): KOGA, Junichiro
!  File : StdoutSubPanel.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.stdout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import ciss.phase_viewer.outputinterface.OutputParser;
import ciss.phase_viewer.outputinterface.OutputParserListener;
import ciss.phase_viewer.plugins.projectmanipulator.phase.resultsviewerpanel.stdout.StdoutGeneralPanel;
import ciss.phase_viewer.plugins.projectmanipulator.phase.resultsviewerpanel.stdout.StdoutSCFPanel;
import ciss.phase_viewer.projectbrowser.ProjectBrowserUtils;
import ciss.phase_viewer.projectbrowser.ProjectInfo;
import ciss.phase_viewer.projectbrowser.tools.NoFilePanel;
import ciss.phase_viewer.projectbrowser.tools.StdoutBasePanel;

/**
 * 
 * @author
 */
public class StdoutSubPanel extends JPanel implements OutputParserListener {
    private Logger logger = Logger.getLogger(StdoutSubPanel.class.getName());
    private ProjectInfo projectInfo;
    private JTabbedPane tabbedPane = new JTabbedPane();
    private StdoutGeneralPanel generalPanel;
    private StdoutSCFPanel tableData;
    private String stdoutFileName = "output000";

    private Vector panels = new Vector();

    private Vector stdoutVector = new Vector();
    private Class[] clazz;

    /** Creates a new instance of StdoutSubPanel */
    public StdoutSubPanel(ProjectInfo projectInfo) {
        this.projectInfo = projectInfo;
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        init();
        add(createSelector());
        createPanels();
        add(Box.createVerticalGlue());
    }

    public StdoutSubPanel(ProjectInfo projectInfo, Class[] clazz) {
        this.projectInfo = projectInfo;
        this.clazz = clazz;
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        init();
        add(createSelector());
        createPanels();
        add(Box.createVerticalGlue());
    }

    private void createPanels() {
        if (stdoutVector.size() == 0) {
            return;
        }
        for (int i = 0; i < panels.size(); i++) {
            StdoutBasePanel panel = (StdoutBasePanel) panels.elementAt(i);
            tabbedPane.addTab(panel.getDescription(), panel);
        }
        add(tabbedPane);
    }

    private JComboBox comboStdout;
    private JTextField filtertext;
    private JCheckBox caseCheckbox;

    private JPanel createSelector() {
        if (stdoutVector.size() == 0) {
            return new NoFilePanel("F_OUT");
        }
        JPanel p = new JPanel();
        // p.setLayout(new BoxLayout(p,BoxLayout.X_AXIS));
        JLabel select = new JLabel(" select stdout file:          ");
        p.add(select);

        comboStdout = new JComboBox(stdoutVector);
        comboStdout.setSize(select.getSize());
        p.add(comboStdout);

        JPanel peditor = new JPanel();
        peditor.setLayout(new BoxLayout(peditor, BoxLayout.X_AXIS));

        JLabel label_filter = new JLabel(" filter: ");
        filtertext = new JTextField(10);

        caseCheckbox = new JCheckBox("ignore case");

        JButton btneditor = new JButton("editor");

        peditor.add(label_filter);
        peditor.add(filtertext);
        peditor.add(caseCheckbox);
        peditor.add(btneditor);
        p.add(peditor);

        btneditor.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                stdoutFileName = projectInfo.getProjectDirectory()
                        + System.getProperty("file.separator")
                        + comboStdout.getSelectedItem();
                String tmp = filtertext.getText();
                if (tmp == null || tmp.trim().length() == 0) {
                    ProjectBrowserUtils.bootTextViewer(stdoutFileName);
                } else {
                    ProjectBrowserUtils.bootTextViewer(stdoutFileName,
                            tmp.trim(), caseCheckbox.isSelected());
                }
            }
        });

        comboStdout.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                stdoutFileName = projectInfo.getProjectDirectory()
                        + System.getProperty("file.separator")
                        + comboStdout.getSelectedItem();
                if (new File(stdoutFileName).exists()) {
                    update(stdoutFileName);
                }
            }
        });
        comboStdout.setSelectedIndex(comboStdout.getItemCount() - 1);
        update(stdoutFileName);

        return p;
    }

    private void init() {
        String name = projectInfo.getChaseFileManager().getFile("F_OUT")
                .getDefaultName().getValue();
        String projdir = projectInfo.getProjectDirectory();
        String path = projdir + System.getProperty("file.separator") + name;

        String[] stdoutfiles = new File(projdir).list();
        if (stdoutfiles == null || stdoutfiles.length == 0) {
            logger.debug("dir " + projdir + " is null/not a directory.");
            return;
        }

        stdoutVector = new Vector();
        for (int i = 0; i < stdoutfiles.length; i++) {
            logger.debug("file : " + stdoutfiles[i]
                    + " the name to be matched: " + name);
            if (stdoutfiles[i].trim().matches(name.trim())) {
                stdoutVector.addElement(stdoutfiles[i]);
                logger.debug("found stdout file!");
            }
        }

        if (stdoutVector.size() == 0) {
            logger.debug("no stdout files...");
            return;
        }
        if (clazz == null)
            return;
        for (int i = 0; i < clazz.length; i++) {
            try {
                // StdoutBasePanel obj =
                // (StdoutBasePanel)PluginLoader.instantiate(clazz[i].getName(),null);
                StdoutBasePanel obj = (StdoutBasePanel) clazz[i].newInstance();
                panels.add(obj);
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    }

    private OutputParser outputParser;

    private void update(String fileName) {
        logger.debug("updating stdout; stdout file : " + fileName);
        // if ( outputParser == null ) {
        outputParser = projectInfo.getOutputInterface().getParser("F_OUT",
                fileName, this);
        // }
        outputParser.setParsed(false);
        outputParser.doParse();
    }

    public void parseFinished() {
        for (int i = 0; i < panels.size(); i++) {
            logger.debug("clazz: " + panels.get(i).getClass().toString());
            StdoutBasePanel p = (StdoutBasePanel) panels.elementAt(i);
            if (p != null) {
                p.setOutputParser(outputParser);
            }
        }
    }

}
