/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/11/15, 18:56
!  AUTHOR(S): KOGA, Junichiro
!  File : JobStatusPanel.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.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.Vector;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

import org.apache.log4j.Logger;

import ciss.phase_viewer.projectbrowser.ProjectInfo;

/**
 * 
 * @author
 */
public class JobStatusPanel extends JPanel {
    private Logger logger = Logger.getLogger(JobStatusPanel.class.getName());

    private ProjectInfo projectInfo;
    private String baseDir;
    private String jobstatusPrefix = "jobstatus";

    private JComboBox jobnoCombo;
    private JPanel timePanel;

    private boolean bjobs = true;
    private JobStatusMonitor monitor;

    public JobStatusPanel(ProjectInfo projectInfo) {
        super();
        this.projectInfo = projectInfo;
        this.baseDir = projectInfo.getProjectDirectory()
                + System.getProperty("file.separator");
        this.setLayout(new GridBagLayout());
        GridBagConstraints cons = new GridBagConstraints();
        cons.fill = GridBagConstraints.HORIZONTAL;

        Vector jobs = StdoutUtils.getStdoutFiles(baseDir);
        bjobs = (jobs.size() != 0);

        if (bjobs) {
            JPanel general = new JPanel();
            general.setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();

            Vector extensions = new Vector();
            for (int i = 0; i < jobs.size(); i++) {
                extensions.addElement(StdoutUtils
                        .getExtensionOfStdout((String) jobs.elementAt(i)));
            }

            jobnoCombo = new JComboBox(extensions);
            JPanel pjobnoCombo = new JPanel();
            pjobnoCombo.setBorder(new TitledBorder("job no."));
            pjobnoCombo.add(jobnoCombo);

            timePanel = new JPanel();
            timePanel.setBorder(new TitledBorder("program start time"));
            timePanel.setLayout(new FlowLayout());

            c.fill = GridBagConstraints.HORIZONTAL;

            c.weightx = 0.1;
            c.gridx = 0;
            c.gridy = 0;
            // general.add(pjobnoCombo,c);

            c.weightx = 1.0;
            c.gridx = 1;
            c.gridy = 0;
            general.add(timePanel, c);

            JPanel jstat = new JPanel();
            if (!checkJobStatusFiles()) {
                JLabel nojs = new JLabel("(no job status file)");
                jstat.add(nojs);
            } else {
                jstat.add(monitor = new JobStatusMonitor(projectInfo));
            }

            cons.weightx = 1.0;

            cons.gridx = 0;
            cons.gridy = 0;
            this.add(general, cons);

            cons.gridx = 0;
            cons.gridy = 1;
            this.add(jstat, cons);

            jobnoCombo.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent e) {
                    String output = "output"
                            + (String) jobnoCombo.getSelectedItem();
                    recreate(output);
                }
            });
            try {
                jobnoCombo.setSelectedIndex(jobnoCombo.getItemCount() - 1);
            } catch (Exception exc) {
                logger.error("operation failed...");
                exc.printStackTrace();
            }
        } else {
            JLabel not_available = new JLabel("(log file not available)");
            this.add(not_available);
            this.add(new JPanel());
            revalidate();
        }
    }

    public void setFileName(String output) {
        recreate(output);
    }

    private void recreate(String output) {
        String path = baseDir + output;
        String name = output;
        if (new File(output).isAbsolute()) {
            path = output;
            name = new File(output).getName();
        }
        String time = StdoutUtils.getTimeFrom(path);
        JLabel timeLabel = new JLabel(time);
        logger.debug("time: " + time);
        timePanel.removeAll();
        timePanel.add(timeLabel);
        if (monitor != null) {
            monitor.setExtension(StdoutUtils.getExtensionOfStdout(name));
        }
        revalidate();
    }

    private boolean checkJobStatusFiles() {
        File baseFile = new File(baseDir);
        File[] files = baseFile.listFiles();
        if (files == null || files.length == 0) {
            logger.warn("no files in project directory: " + baseDir);
            return false;
        }

        String jobstatReg = jobstatusPrefix + "\\d+";
        Vector jobstatusFiles = new Vector();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            logger.debug("file.getName, reg: " + file.getName() + " "
                    + jobstatReg);
            if (file.getName().matches(jobstatReg)) {
                jobstatusFiles.addElement(file.getName());
            }
        }

        if (jobstatusFiles.size() == 0) {
            return false;
        }

        return true;
    }

}
