/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/06/17, 11:38
!  AUTHOR(S): KOGA, Junichiro
!  File : XMLUtils.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.jdom;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;

import javax.swing.table.TableModel;

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

/**
 * utility methods for parsing/reading xml files.
 * 
 * @author KOGA, Junichiro
 */
public class XMLUtils {
    private static Logger logger = Logger.getLogger(XMLUtils.class.getName());

    private XMLUtils() {
    }

    public static Element getContent(Document doc, String ident) {
        java.util.List list = null;
        try {
            list = doc.getContent();
        } catch (IllegalStateException exc) {
            return null;
        }
        if (list == null || list.size() == 0) {
            Element host = new Element(ident);
            doc.addContent(host);
            return host;
        } else {
            for (int i = 0; i < list.size(); i++) {
                Object obj = list.get(i);
                if (obj instanceof Element) {
                    Element elem = (Element) obj;
                    if (elem.getName().equals(ident)) {
                        return elem;
                    }
                }
            }
        }
        Element host = new Element(ident);
        doc.addContent(host);
        return host;
    }

    public static Document getDocumentFromURL(URL url) {
        Document doc = null;
        SAXBuilder builder = new SAXBuilder();
        if (url == null) {
            return null;
        }
        try {
            doc = builder.build(url);
        } catch (JDOMException jde) {
            logger.error("failed to parse " + url);
            logger.error("unrecoverable error.");
            jde.printStackTrace();
            return null;
        } catch (IOException ioe) {
            logger.error("failed to parse " + url);
            logger.error("unrecoverable error.");
            ioe.printStackTrace();
            return null;
        }
        return doc;
    }

    public static Document getDocumentFromFile(File file) {
        Document doc = null;
        if (file == null || !file.exists()) {
            return null;
        }
        SAXBuilder builder = new SAXBuilder();
        try {
            doc = builder.build(file);
        } catch (Exception jde) {
            logger.error("failed to parse " + file);
            logger.error("unrecoverable error.");
            jde.printStackTrace();
            return null;
        }
        return doc;
    }

    public static void saveDocumentTo(Document doc, String file) {
        saveDocumentTo(doc, new File(file));
    }

    public static void saveDocumentTo(Document doc, File file) {
        FileWriter writer = null;
        logger.debug("saving document to: " + file.getAbsolutePath());

        if (file.exists() && !file.canWrite())
            return;

        try {
            writer = new FileWriter(file);
            XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
            outputter.output(doc, writer);
        } catch (IOException ioe) {
            // logger.warn("failed to save document: "+file.getAbsolutePath());
            logger.warn("cannot save to file " + file.getAbsolutePath());
            // ioe.printStackTrace();
        } catch (NullPointerException npe) {
            // npe.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    public static Element[] getElementsFromTableModel(TableModel model,
            String rowname) {
        int numrow = model.getRowCount();
        Element[] ret = new Element[numrow];
        if (model == null) {
            logger.error("'table model' is null.");
            return null;
        }
        int numcol = model.getColumnCount();
        for (int i = 0; i < numrow; i++) {
            Element elemroot = new Element(rowname);
            for (int j = 0; j < numcol; j++) {
                String colname = model.getColumnName(j);
                Element element = new Element(colname);
                Object obj = model.getValueAt(i, j);
                String sobj = "";
                if (obj instanceof String) {
                    sobj = (String) obj;
                } else if (obj instanceof Boolean) {
                    sobj = ((Boolean) obj).toString();
                }
                element.addContent(MyElement.encode(sobj));
                elemroot.addContent(element);
            }
            ret[i] = elemroot;
        }

        return ret;
    }

}
