/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/08/16, 18:39
!  AUTHOR(S): KOGA, Junichiro
!  File : StdoutUtils.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.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Calendar;
import java.util.Vector;

import org.apache.log4j.Logger;

/**
 * a set of static methods for the standard output file of phase (output\d+
 * files)
 * 
 * @author KOGA, Junichiro
 */
public class StdoutUtils {
    private static Logger logger = Logger
            .getLogger(StdoutUtils.class.getName());

    private StdoutUtils() {
    }

    /**
     * returns a Vector of output+++ or output_+++ files
     * 
     * @param dir
     *            the directory from which output+++ files are searched.
     * @return a Vector of output+++ files.
     */
    public static Vector getStdoutFiles(String dir) {
        Vector vector = new Vector();
        File[] list = (new File(dir)).listFiles();
        for (int i = 0; i < list.length; i++) {
            if (isStdout(list[i].getName())) {
                vector.addElement(list[i].getName());
            }
        }
        return vector;
    }

    /**
     * returns the extention of an output+++ file.
     * 
     * @param output
     *            the output+++ file from which the extention is created.
     * @return the extention (a String representation of a three-digit number)
     */
    public static String getExtensionOfStdout(String output) {
        String ret = new String();
        char[] ch = output.toCharArray();
        if (ch.length == 9) {
            ret = String.copyValueOf(output.toCharArray(), 6, 3);
        }
        return ret;
    }

    /**
     * returns the "program start time" written in an output+++ file.
     * 
     * @param output
     *            the output+++ file from which the program start time is read.
     * @return a String representation of time.
     */
    public static String getTimeFrom(String output) {
        try {
            String ret = "";
            String readString = "";
            BufferedReader br = new BufferedReader(new FileReader(output));
            while ((readString = br.readLine()) != null) {
                if (readString.trim().startsWith("program start")) {
                    String[] line = readString.split("\\s+");
                    if (line.length >= 4) {
                        ret = line[2] + " " + line[3];
                        return transformToDate(ret);
                    }
                }
            }
            br.close();
        } catch (Exception exc) {
            logger.error("failed to read " + output);
        }
        return "(not available)";
    }

    private static String transformToDate(String rawDate) {
        Calendar calendar = Calendar.getInstance();
        String[] string0 = rawDate.split("\\s+");
        String[] string1 = string0[0].split(":");
        String[] string2 = string0[1].split("/");
        try {
            calendar.set(Integer.parseInt(string2[2]),
                    Integer.parseInt(string2[1]) - 1,
                    Integer.parseInt(string2[0]), Integer.parseInt(string1[0]),
                    Integer.parseInt(string1[1]), Integer.parseInt(string1[2]));
        } catch (Exception exc) {
            return rawDate;
        }

        return calendar.getTime().toString();
    }

    private static boolean isStdout(String file) {
        String identOut = "output";
        String underScore = "_";

        int lenOutput = 6;
        int lenNumber = 3;
        int minimumLength = 9;
        int maximumLength = 10;

        char[] ch = file.toCharArray();

        // check if the file has an appropriate ``length''
        if (ch.length < minimumLength || ch.length > maximumLength) {
            return false;
        }

        // check if file starts with ``output''
        String ident = String.copyValueOf(ch, 0, lenOutput);
        if (!ident.equals(identOut)) {
            return false;
        }

        // check if file is an ``output_000'' file
        if (file.equals("output_000")) {
            return true;
        }

        // check if file is an ``output+number'' file
        return file.trim().matches("output\\d+");
    }

}
