/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/11/30, 19:06
!  AUTHOR(S): KOGA, Junichiro
!  File : DataSetImporter.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.graph.dataset;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;

import org.apache.log4j.Logger;

/**
 * データセットをインポート.
 * 
 * @author
 */
public class DataSetImporter {
    private Logger logger = Logger.getLogger(DataSetImporter.class.getName());
    private DataSet dset;
    private String fileName;
    private String HASH = "#";

    /** Creates a new instance of DataSetImporter */
    public DataSetImporter(String fileName) {
        this.fileName = fileName;
        dset = new DataSet(new File(fileName).getName());
        dset.setFileName(fileName);
        doImport();
    }

    private void doImport() {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(fileName));
            String firstLine = reader.readLine().trim();
            String[] idents = null;
            if (firstLine.startsWith(HASH)) {
                if (firstLine.length() > 1) {
                    String hoge = firstLine.trim().substring(1,
                            firstLine.length());
                    String[] foo = firstLine.split(HASH);
                    if (foo != null && foo.length != 0) {
                        idents = hoge.trim().split("\\s+");
                    }
                }
            }
            if (idents == null) {
                logger.debug("null identifier");
                reader = new BufferedReader(new FileReader(fileName));
            }
            // for ( int i=0 ; i<idents.length ; i++ ) {
            // logger.debug("ident no. "+i+": "+idents[i]);
            // }
            String line = "";
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.length() != 0) {
                    parseLine(line);
                }
            }

            if (dataVector.size() == 0) {
                return;
            }

            if (idents == null) {
                int ncol = ((String[]) dataVector.elementAt(0)).length;
                idents = new String[ncol];
                String elem = "element";
                for (int i = 0; i < ncol; i++) {
                    idents[i] = elem + String.valueOf(i);
                }
            }

            String[][] data = new String[idents.length][dataVector.size()];
            for (int i = 0; i < dataVector.size(); i++) {
                String[] row = (String[]) dataVector.elementAt(i);
                int numcol = row.length;
                if (numcol > idents.length) {
                    numcol = idents.length;
                }
                for (int j = 0; j < numcol; j++) {
                    data[j][i] = row[j];
                }
            }

            for (int i = 0; i < idents.length; i++) {
                DataSetElement dse = new DataSetElement(data[i], idents[i],
                        dset);
                dset.addData(dse);
            }
            logger.info("finishied import of dataset from file: " + fileName);
        } catch (IOException ioe) {
            logger.error("encountered error during import of file: " + fileName);
            ioe.printStackTrace();
            dset = null;
            return;
        } catch (ArrayIndexOutOfBoundsException aoi) {
            dset = null;
            logger.error("inconsistent data");
        } finally {
            try {
                reader.close();
            } catch (IOException ioe) {
            }
        }
    }

    private Vector dataVector = new Vector();

    private void parseLine(String line) {
        String[] array = line.split("\\s+");
        if (array == null || array.length == 0) {
            array = line.split(",");
        }
        if (array == null || array.length == 0) {
            return;
        }
        for (int i = 0; i < array.length; i++) {
            try {
                Double.parseDouble(array[i]);
            } catch (NumberFormatException nfe) {
                return;
            }
        }
        dataVector.addElement(array);
    }

    public DataSet getDataSet() {
        return dset;
    }

}
