/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/10/16, 19:16
!  AUTHOR(S): KOGA, Junichiro
!  File : PseudoPotChecker.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.inputcheck;

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

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.Utils;
import ciss.phase_viewer.input.PhaseInputChecker;
import ciss.phase_viewer.inputinterface.InputInterfacePrimitiveEntry;
import ciss.phase_viewer.inputinterface.inputinterfacetable.InputInterfaceTable;

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

    /** Creates a new instance of PseudoPot */
    public PseudoPotChecker() {
    }

    public boolean isFixable() {
        return true;
    }

    public String getName() {
        return "pseudopotential specification";
    }

    public String getDescription() {
        return "check whether the specification of the PPs is valid.";
    }

    public String getCandidate() {
        if (state != OK)
            return "will correct pp file specification";

        return "";
    }

    private boolean isLDA() {
        boolean isLDA = false;
        inputInterface.selectRoot();
        inputInterface.selectBlock("accuracy");
        InputInterfacePrimitiveEntry prim = inputInterface
                .getPrimitiveEntry("xctype");
        if (prim.getValue().toLowerCase().startsWith("lda"))
            isLDA = true;
        inputInterface.selectRoot();
        return isLDA;
    }

    private String getXCType() {
        inputInterface.selectRoot();
        inputInterface.selectBlock("accuracy");
        InputInterfacePrimitiveEntry prim = inputInterface
                .getPrimitiveEntry("xctype");
        String ret = prim.getValue();
        inputInterface.selectRoot();
        return ret;
    }

    public boolean fixInput() {
        InputInterfaceTable elemtable = inputInterface
                .getInputInterfaceTable("structure.element_list");
        int elemind = elemtable.getIndexFor("element");
        Vector data = elemtable.getTableData();
        String ppdir = Utils.getDefaultPPDir();
        String relpath = Utils.getRelativePath(projDir, ppdir).replaceAll(
                "\\\\", "/");

        Vector vec = new Vector();
        boolean isLDA = isLDA();
        for (int i = 0; i < data.size(); i++) {
            String elemName = Utils
                    .stripNumber(((String[]) data.get(i))[elemind]);
            String[] pps = Utils.getPPCandidates(elemName);
            if (pps == null || pps[0].equals(Utils.NO_CANDIDATE)) {
                logger.error("could not find pp file for element " + elemName);
                return false;
            }
            String newestPP = pps[pps.length - 1];
            if (isLDA) {
                for (int j = pps.length - 1; j >= 0; j--) {
                    if (pps[j].toLowerCase().indexOf("lda") > 0) {
                        newestPP = pps[j];
                        break;
                    }
                }
            }
            vec.addElement(relpath + "/" + newestPP);
        }
        String fdata = "";
        try {
            BufferedReader rd = new BufferedReader(
                    new FileReader(fileNamesData));
            String line = "";
            while ((line = rd.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("F_POT") || line.startsWith("/")
                        || line.startsWith("&end"))
                    continue;
                fdata += line + System.getProperty("line.separator");
            }
            rd.close();
            for (int i = 0; i < vec.size(); i++) {
                fdata += "F_POT(" + String.valueOf(i + 1) + ") = '"
                        + vec.get(i).toString() + "'"
                        + System.getProperty("line.separator");
            }
            fdata += "/";
            PrintWriter wr = new PrintWriter(new FileWriter(fileNamesData));
            wr.print(fdata);
            wr.flush();
            wr.close();
        } catch (IOException ioe) {
            logger.error("failed to manipulate file_names.data");
            ioe.printStackTrace();
            return false;
        }
        return true;
    }

    public int doCheck() {
        String[] pots = getAllFilePath("F_POT(");
        if (pots == null) {
            message = "no ppfiles specified in file_names.data";
            return ERROR;
        }

        InputInterfaceTable elemtable = inputInterface
                .getInputInterfaceTable("structure.element_list");
        int elemind = elemtable.getIndexFor("element");
        Vector data = elemtable.getTableData();

        if (pots.length != data.size()) {
            message = "number of elements and pp files are inconsistent";
            return ERROR;
        }

        String xctype = getXCType();
        for (int i = 0; i < data.size(); i++) {
            String elemName = Utils
                    .stripNumber(((String[]) data.get(i))[elemind]);
            String potelemname = new File(pots[i]).getName().split("_")[0];
            if (!elemName.equalsIgnoreCase(potelemname)) {
                message = "element block and pp specifications are inconsistent";
                return ERROR;
            }
            if (xctype.toLowerCase().trim().startsWith("lda")
                    && pots[i].toLowerCase().indexOf("lda") < 0) {
                message = "accuracy.xctype is LDA, but " + pots[i]
                        + " is not an LDA pp file";
                return ERROR;
            } else if (xctype.toLowerCase().trim().startsWith("gga")
                    && pots[i].toLowerCase().indexOf("gga") < 0) {
                message = "accuracy.xctype is GGA, but " + pots[i]
                        + " is not a GGA pp file";
                return ERROR;
            }
        }

        return OK;
    }

}
