/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/07/12, 19:33
!  AUTHOR(S): KOGA, Junichiro
!  File : ProjectManipulator.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.projectbrowser;

import java.awt.Dimension;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import javax.swing.JPanel;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import ciss.phase_viewer.jdom.MyElement;
import ciss.phase_viewer.main.PluginLoader;
import ciss.phase_viewer.projectbrowser.projectdirbrowser.ProjectDirBrowserNode;

/**
 * 
 * @author KOGA, Junichiro
 */
abstract public class ProjectManipulator extends JPanel {
    private static Logger logger = Logger.getLogger(ProjectManipulator.class
            .getName());
    public static String PROJECT_MANIPULATOR_XML_PATH = "/ciss/phase_viewer/projectbrowser/ProjectManipulator.xml";
    protected ProjectInfo projectInfo;
    protected Object[] args;

    protected static final String FS = System.getProperty("file.separator");

    /** Creates a new instance of ProjectManipulator */
    public ProjectManipulator(ProjectInfo projectInfo) {
        this.projectInfo = projectInfo;
    }

    public ProjectManipulator(ProjectInfo projectInfo, Object[] args) {
        this.projectInfo = projectInfo;
        this.args = args;
    }

    public static ProjectManipulator createProjectManipulator(ProjectInfo info) {
        String type = info.getProjectType();
        URL projurl = null;

        // try {
        // projurl = new URL(ProjectManipulator.PROJECT_MANIPULATOR_XML_PATH);
        projurl = ProjectManipulator.class
                .getResource(PROJECT_MANIPULATOR_XML_PATH);
        // } catch(MalformedURLException e) {
        // logger.error("malformed url: "+ProjectManipulator.PROJECT_MANIPULATOR_XML_PATH);
        // }

        Document doc = null;
        SAXBuilder builder = new SAXBuilder();
        try {
            doc = builder.build(projurl);
        } catch (JDOMException jde) {
            logger.error("failed to parse " + projurl);
            logger.error("unrecoverable error.");
        } catch (IOException ioe) {
            logger.error("failed to parse " + projurl);
            logger.error("unrecoverable error.");
        }

        Element elem = doc.getRootElement();
        if (!elem.getName().equals("root")) {
            logger.error("invalid ProjectSpecification file.");
        }

        List list = elem.getChildren("project");
        String loadclass = null;
        for (int i = 0; i < list.size(); i++) {
            Element element = (Element) list.get(i);
            String name = MyElement.decode(element.getChildTextTrim("name"));
            if (name.equals(type)) {
                loadclass = element.getChildTextTrim("loadclass");
                Element initSize = element.getChild("init_size");
                if (initSize != null) {
                    String si = initSize.getTextTrim();
                    String[] sizr = si.split(",");
                    if (sizr != null && sizr.length >= 2) {
                        try {
                            Dimension initBrowserSize = new Dimension(
                                    Integer.parseInt(sizr[0]),
                                    Integer.parseInt(sizr[1]));
                            info.setInitialBrowserSize(initBrowserSize);
                        } catch (Exception exc) {
                        }
                    }
                }
                break;
            }
        }

        if (loadclass == null) {
            logger.error("failed to get a valid class name to load.");
        }
        if (loadclass.equalsIgnoreCase("null")) {
            return null;
        }

        ProjectManipulator manip = (ProjectManipulator) PluginLoader
                .instantiate(loadclass, new Object[] { info });
        return manip;
    }

    /**
     * Called every time (probably) when a concrete implementation of this class
     * is instanciated. Should be called AFTER initializeProject method when a
     * sub project is newly created.
     */
    abstract public void init();

    /**
     * Called from SubProjectCreator#createElement() perform any initialization
     * that should be performed when a new sub project is created.
     */
    abstract public void initializeProject();

    /**
     * Called from SubProjectCreator#createElement() perform any initialization
     * that should be performed when a new sub project is created. will do
     * nothing on default.
     * 
     * @param node
     *            a node from which the project was called.
     */
    public void initializeProject(ProjectDirBrowserNode node) {
    }

    /**
     * Called when the parent component is closing ... not abstract since not
     * all components need this functionality, but make sure you override this
     * method if you want, for instance, to save some setting files on close.
     */
    public boolean postProcess() {
        return true;
    }

    /**
     * override this method if you have to recreate this gui.
     */
    public void recreate() {
    }

    /**
     * override this method if you want to change something right after
     * instatiation.
     */
    public void postInit() {
    }

    /**
     * override this method if you want to do something right after each button
     * press
     * 
     */
    public void buttonPressed() {
    }

    /**
     * called after this GUI has been set.
     */
    public void componentSet() {
    }

}
