/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/08/16, 18:10
!  AUTHOR(S): KOGA, Junichiro
!  File : JobStatusMonitor.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.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import org.apache.log4j.Logger;

import ciss.phase_viewer.projectbrowser.ProjectInfo;

/**
 * 
 * @author KOGA, Junichiro
 */
public class JobStatusMonitor extends JPanel {
    private Logger logger = Logger.getLogger(JobStatusMonitor.class.getName());

    private TFJobStatus status;
    private TFJobStatus iteration;
    private TFJobStatus iter_ionic;
    private TFJobStatus iter_elec;
    private TFJobStatus elapsed_time;

    private final int REFRESH = 5000;

    private String statusFile;
    private String extension;
    private String baseDir;

    /** Creates a new instance of JobStatusMoniter */
    public JobStatusMonitor(ProjectInfo projectInfo) {
        super();
        this.baseDir = projectInfo.getProjectDirectory()
                + System.getProperty("file.separator");
        this.setLayout(new GridLayout(1, 1));

        createPanels();

        javax.swing.Timer timer = new javax.swing.Timer(REFRESH,
                new ActionListener() {
                    public void actionPerformed(ActionEvent ev) {
                        reload();
                    }
                });

        timer.start();
    }

    public void setExtension(String extension) {
        this.extension = extension;
        statusFile = baseDir + "jobstatus" + extension;
        if (extension.trim().length() == 0) {
            logger.warn("jobstatus file: not available");
            return;
        }
        reload();
    }

    private void reload() {
        if (statusFile == null) {
            return;
        }
        File file = new File(statusFile);
        boolean statusExists = file.exists();
        String str_status = new String();
        String str_iteration = new String();
        String str_iter_ionic = new String();
        String str_iter_elec = new String();
        String str_elapsed_time = new String();

        if (statusExists) {
            addPanels();
            try {
                String readString;
                BufferedReader br = new BufferedReader(new FileReader(
                        statusFile));
                while ((readString = br.readLine()) != null) {
                    StringTokenizer st = new StringTokenizer(readString, "=");
                    if (st.countTokens() >= 2) {
                        String ident = st.nextToken().trim();
                        if (ident.equals("status")) {
                            str_status = st.nextToken().trim();
                        } else if (ident.equals("iteration")) {
                            str_iteration = st.nextToken().trim();
                        } else if (ident.equals("iter_ionic")) {
                            str_iter_ionic = st.nextToken().trim();
                        } else if (ident.equals("iter_elec")) {
                            str_iter_elec = st.nextToken().trim();
                        } else if (ident.equals("elapsed_time")) {
                            str_elapsed_time = st.nextToken().trim();
                        }
                    }
                }
                br.close();
                this.setBorder(new TitledBorder("jobstatus file: jobstatus"
                        + extension));
            } catch (Exception exc) {
                logger.error("failed read from: " + statusFile);
            }
        } else {
            addPanels();
            this.setBorder(new TitledBorder("jobstatus file: jobstatus"
                    + extension + " not available"));
        }

        status.setText(str_status);
        iteration.setText(str_iteration);
        iter_ionic.setText(str_iter_ionic);
        iter_elec.setText(str_iter_elec);
        elapsed_time.setText(str_elapsed_time);
        revalidate();
    }

    private void createPanels() {
        this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

        int width = 13;

        status = new TFJobStatus("status", width);
        iteration = new TFJobStatus("iteration", width);
        iter_ionic = new TFJobStatus("iter_ionic", width);
        iter_elec = new TFJobStatus("iter_elec", width);
        elapsed_time = new TFJobStatus("elapsed_time", width);
    }

    private void addPanels() {
        this.removeAll();
        JPanel p = new JPanel();
        p.add(status);
        p.add(iteration);
        p.add(iter_ionic);
        p.add(iter_elec);
        p.add(elapsed_time);
        this.add(p);
    }

    private void addNotAvailable() {
        this.removeAll();
        this.add(new JLabel("(jobstatus" + extension + ": not available)"));
    }

}

class TFJobStatus extends JTextField {
    public TFJobStatus(String title, int column) {
        super(column);
        this.setEditable(false);
        this.setHorizontalAlignment(JTextField.CENTER);
        Font font = new Font("Monospaced", Font.BOLD, 12);
        this.setFont(font);
        TitledBorder titledBorder = new TitledBorder(title);
        titledBorder.setTitleFont(font);
        this.setBorder(titledBorder);
    }
}
