/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/06/02, 18:38
!  AUTHOR(S): KOGA, Junichiro
!  File : PhaseFileManager.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.phase;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.util.StringTokenizer;
import java.util.Vector;

import org.apache.log4j.Logger;

import ciss.phase_viewer.file.ChaseFile;
import ciss.phase_viewer.file.ChaseFileManager;
import ciss.phase_viewer.ssh.hosts.HostInfo;

/**
 * PHASE用のChaseFileManagerの実装. 本当に良くなってるのか?
 * 
 * @author
 */
public class PhaseFileManager extends ChaseFileManager {
    private Logger logger = Logger.getLogger(PhaseFileManager.class.getName());
    private String programName = "phase";

    /** Creates a new instance of PhaseFileManager */
    public PhaseFileManager(HostInfo hostInfo, URL specFile, File fileSpecFile) {
        super(hostInfo, specFile, fileSpecFile);
    }

    public PhaseFileManager(URL specFile, File fileSpecFile) {
        super(specFile, fileSpecFile);
    }

    private void saveFileNamesData() {
        int potcount = 1;
        PrintWriter fout = null;

        if (fileSpecFile.exists() && !fileSpecFile.canWrite()) {
            logger.debug(fileSpecFile.getAbsolutePath()
                    + " exists but cannot be written.");
            return;
        }

        try {
            fout = new PrintWriter(new BufferedWriter(new FileWriter(
                    fileSpecFile)));
            fout.println("&fnames");
            ChaseFile[] files = getFiles();
            Vector strvec = new Vector();
            for (int i = 0; i < files.length; i++) {
                ChaseFile file = files[i];
                if (file.getFileNameEditLevel().equals(ChaseFile.NEVER)) {
                    continue;
                }
                String ident = file.getIdentifier().getValue();
                String relative_path = file.getRelativePath();
                relative_path = relative_path.replaceAll("\\\\", "/");
                String na = file.getFileName();
                if (!ident.startsWith("F_POT(")) {
                    strvec.add(ident + " = \'" + relative_path + "/" + na
                            + "\'");
                    // fout.println(ident+" = \'"+relative_path+"/"+na+"\'");
                    logger.debug(ident + " = \'" + relative_path + "/" + na
                            + "\'");
                }
            }

            for (int i = 0; i < files.length; i++) {
                ChaseFile file = files[i];
                if (file.getFileNameEditLevel().equals(ChaseFile.NEVER)) {
                    continue;
                }
                String ident = file.getIdentifier().getValue();
                String relative_path = file.getRelativePath();
                relative_path = relative_path.replaceAll("\\\\", "/");
                String na = file.getFileName();
                if (ident.startsWith("F_POT")) {
                    String filename = relative_path + "/" + na;
                    String pot = "F_POT("
                            + String.valueOf(String.valueOf(potcount))
                            + ") = \'" + filename + "\'";
                    if (strvec.size() > potcount)
                        strvec.add(potcount, pot);
                    else
                        strvec.add(pot);
                    // fout.println(pot);
                    logger.debug(pot);
                    potcount++;
                }
            }

            for (int i = 0; i < strvec.size(); i++)
                fout.println(strvec.get(i).toString());

            fout.println("/");

            fout.flush();
        } catch (Exception exc) {
            logger.warn("file in use?");
            // exc.printStackTrace();
            // System.out.println("failed write to:
            // "+fileSpecFile.getAbsolutePath());
        } finally {
            if (fout != null) {
                fout.close();
            }
        }
    }

    // private void saveFileNamesData() {
    // int potcount = 1;
    // PrintWriter fout = null;
    //
    // if ( fileSpecFile.exists() && !fileSpecFile.canWrite() ) {
    // logger.debug(fileSpecFile.getAbsolutePath()+" exists but cannot be written.");
    // return;
    // }
    //
    // try {
    // fout = new PrintWriter(new BufferedWriter(new FileWriter(fileSpecFile)));
    // fout.println("&fnames");
    // ChaseFile [] files = getFiles();
    // for ( int i=0 ; i<files.length ; i++ ) {
    // ChaseFile file = files[i];
    // if ( file.getFileNameEditLevel().equals(ChaseFile.NEVER) ) {
    // continue;
    // }
    // String ident = file.getIdentifier().getValue();
    // String relative_path = file.getRelativePath();
    // relative_path=relative_path.replaceAll("\\\\","/");
    // String na = file.getFileName();
    // if ( !ident.startsWith("F_POT(") ) {
    // fout.println(ident+" = \'"+relative_path+"/"+na+"\'");
    // logger.debug(ident+" = \'"+relative_path+"/"+na+"\'");
    // } else {
    // String projdir = projectInfo.getProjectDirectory();
    // String strpp = Utils.getDefaultPPDir();
    // String dir = Utils.getRelativePath(projdir,strpp,true);
    // String filename = relative_path+"/"+na;
    // String pot =
    // "F_POT("+String.valueOf(String.valueOf(potcount))+") = \'"+filename+"\'";
    // fout.println(pot);
    // logger.debug(pot);
    // potcount++;
    // }
    // }
    // fout.println("/");
    // fout.flush();
    // } catch(Exception exc) {
    // logger.warn("file in use?");
    // //exc.printStackTrace();
    // //System.out.println("failed write to: "+fileSpecFile.getAbsolutePath());
    // } finally {
    // if ( fout != null ) {
    // fout.close();
    // }
    // }
    // }

    public void saveSub() {
        saveFileNamesData();
    }

    public String getName() {
        return "phase";
    }

    protected void postInit() {
    }

    protected void postRead() {
        readFileNamesData();
    }

    private void readFileNamesData() {
        if (!fileSpecFile.exists()) {
            logger.debug("no fileSpecFile.");
            return;
        }
        try {
            BufferedReader br = new BufferedReader(new FileReader(fileSpecFile));
            String entry;
            while ((entry = br.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(entry, "=");
                if (st.countTokens() >= 2) {
                    String ident = st.nextToken().trim();
                    String value = st.nextToken().replace('\'', ' ').trim();
                    String fname = new File(value).getName();
                    String path = new File(value).getParent();
                    super.updateFile(ident, fname, "filename", fname);
                    super.updateFile(ident, fname, "relative_path", path);
                    logger.debug("path, fname: " + fname + ", " + path);
                }
            }
            br.close();
        } catch (Exception e) {
            logger.error("failed read from: " + fileSpecFile.getAbsolutePath());
            e.printStackTrace();
        }
    }

    public String getBaseDirectory() {
        return fileSpecFile.getParent();
    }

}
