/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/12/21, 13:34
!  AUTHOR(S): KOGA, Junichiro
!  File : JobController.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.jobcontrol;

import java.io.File;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;

import ciss.phase_viewer.projectbrowser.ProjectInfo;
import ciss.phase_viewer.ssh.hosts.HostInfo;
import ciss.phase_viewer.ssh.remotehostexecuter.BatchFileTransferer;
import ciss.phase_viewer.ssh.remotehostexecuter.JobExecuter;

/**
 * ジョブを制御するクラス. ジョブの詳細な振る舞いは具体的に発行するスクリプトに依存する.
 * 
 * @author
 */
public class JobController {
    private static Logger logger = Logger.getLogger(JobController.class
            .getName());
    public static String JOBCONTROL_FILE = "phase-viewer.xml";
    public static String ROOT = "project";
    public static String JOBCONTROL = "jobcontrol";
    private String baseDir;

    /**
     * ジョブを投げる際のベースとなるディレクトリー.
     */
    public JobController(String baseDir) {
        this.baseDir = baseDir;
    }

    /**
     * JobControlFileの取得. 必要に応じて初期化なども行う.
     * 
     * @param projectInfo
     *            プロジェクト情報
     */
    public static Document getJobControlDocument(ProjectInfo projectInfo,
            JobControllerElement element) {
        String dir = projectInfo.getProjectDirectory();
        Document doc = projectInfo.getProjectPropertyDocument();

        if (doc == null) {
            File xmlfile = new File(dir + System.getProperty("file.separator")
                    + JOBCONTROL_FILE);
            doc = ciss.phase_viewer.jdom.XMLUtils.getDocumentFromFile(xmlfile);
        }

        if (!doc.hasRootElement()) {
            Element root = getRootElement();
            doc.setRootElement(root);
        }

        Element jobcontrol = doc.getRootElement().getChild(JOBCONTROL);
        if (jobcontrol == null) {
            jobcontrol = new Element(JOBCONTROL);
            doc.getRootElement().addContent(jobcontrol);
        }

        if (!element.readJobControlDocument(doc)) {
            logger.debug("failed to read job-control element : "
                    + element.getClass().getName());
            element.initJobControlDocument(doc);
            ciss.phase_viewer.jdom.XMLUtils.saveDocumentTo(doc,
                    dir + System.getProperty("file.separator")
                            + JOBCONTROL_FILE);
            element.readJobControlDocument(doc);
        }

        return doc;
    }

    /**
     * ProjectInfoからDocumentを取得し, phase-viewer.xmlなるファイルを保存する. これで大抵はうまくいくはず?
     * 
     * @param projectInfo
     *            プロジェクト情報
     */
    public static void saveJobControlFile(ProjectInfo projectInfo) {
        Document doc = projectInfo.getProjectPropertyDocument();
        String baseDir = projectInfo.getProjectDirectory();
        ciss.phase_viewer.jdom.XMLUtils.saveDocumentTo(doc,
                baseDir + System.getProperty("file.separator")
                        + JOBCONTROL_FILE);
    }

    /**
     * JobControlファイルをディスクへ保存する.
     * 
     * @param dir
     *            保存したいディレクトリー
     * @param doc
     *            保存したい内容の書いてあるDocument
     */
    public static void saveJobControlFile(String dir, Document doc) {
        File jobcont = new File(dir + System.getProperty("file.separator")
                + JOBCONTROL_FILE);
        if (jobcont.exists() && jobcont.canWrite())
            ciss.phase_viewer.jdom.XMLUtils.saveDocumentTo(doc,
                    dir + System.getProperty("file.separator")
                            + JOBCONTROL_FILE);
    }

    /**
     * JobControl用ファイルのRootエレメントを返す.
     * 
     * @return JobControl用ファイルのRootエレメント
     */
    public static Element getRootElement() {
        Element element = new Element(ROOT);
        return element;
    }

    /**
     * Job実行
     */
    public static boolean execute(ProjectInfo projectInfo, HostInfo hostInfo) {
        logger.info("start job execution");
        BatchFileTransferer batchTransfer = new BatchFileTransferer(
                projectInfo, hostInfo);
        JobExecuter executer = new JobExecuter(projectInfo, hostInfo,
                batchTransfer);
        boolean ret = executer.execute();
        return ret;
    }

}
