/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package XmlTest1;

import WebScraping.SearchData;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author kgto
 */
public class XmlSearchDataRW2 {

    DocumentBuilder builder;
    Document document;
    Element root;
    
    public XmlSearchDataRW2() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            builder = factory.newDocumentBuilder();
            
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XmlSearchDataRW2.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public String loadUrl() {
        String urladdress;
        
        NodeList nodelist = root.getElementsByTagName("url");
        Node node = nodelist.item(0);
        urladdress = node.getFirstChild().getNodeValue();
        
        return urladdress;
    }
    
    public ArrayList<SearchData> loadSearchList() {
        ArrayList<SearchData> slist = new ArrayList<>();
        
        NodeList nodelist = root.getElementsByTagName("searchlist");
        for(int i = 0; i < nodelist.getLength(); i++) {
            Node childnode = nodelist.item(i);
            
            boolean sdatflg = false;
            SearchData sdat = new SearchData();
            
            //NodeList childnodelist = childnode.getChildNodes();
            //for(int j = 0; j < childnodelist.getLength(); j++) {
            //    Node child = childnodelist.item(j);
            
            for (Node child = childnode.getFirstChild(); 
                    child != null; child = child.getNextSibling()) {
                
                if(child.getNodeType() == Node.ELEMENT_NODE) {
                    
                    String tag = child.getNodeName();
                    String rtn = "";
                    if(child.getFirstChild() != null) {
                        rtn = child.getFirstChild().getNodeValue();
                    }

                    switch (tag) {
                        case "item" :
                            sdat.setitem(rtn);
                            sdatflg = true;
                            break;
                        case "htmltag" :
                            sdat.setHtmltag(rtn);
                            sdatflg = true;
                            break;
                        case "htmlid" :
                            sdat.setHtmlid(rtn);
                            sdatflg = true;
                            break;
                        case "htmlclass" :
                            sdat.setHtmlclass(rtn);
                            sdatflg = true;
                            break;
                        case "around" :
                            sdat.setaround(rtn);
                            sdatflg = true;
                            break;
                        case "regexp" :
                            sdat.setregexp(rtn);
                            sdatflg = true;
                            break;
                    }
                }
            }
            if(sdatflg) slist.add(sdat);
        }
        return slist;
    }
    
    public void saveUrl(String urladdress) {
        checkdoc();
        removeElement("url");    // 既にElementが存在してた場合、一度削除
        
        Element url = document.createElement("url");
        url.appendChild(document.createTextNode(urladdress));
        root.appendChild(url);
        
    }
    
    public void saveSearchList(ArrayList slist) {
        checkdoc();
        removeElement("searchlist");    // 既にElementが存在してた場合、一度削除
        
        for (Object slist1 : slist) {
            SearchData sdat = (SearchData) slist1;
            
            Element cslist    = document.createElement("searchlist");

            addChild(cslist, "item", sdat.getitem());
            addChild(cslist, "htmltag", sdat.getHtmltag());
            addChild(cslist, "htmlid", sdat.getHtmlid());
            addChild(cslist, "htmlclass", sdat.getHtmlclass());
            addChild(cslist, "around", sdat.getaround());
            addChild(cslist, "regexp", sdat.getregexp());

            root.appendChild(cslist);
        }
        
    }
    
    private void addChild(Element cslist, String keyword, String data) {
        if(!data.isEmpty()) {
            Element element = document.createElement(keyword);
            element.appendChild(document.createTextNode(data));
            cslist.appendChild(element);
        }
    }
    
    private void removeElement(String elementTagName) {
        NodeList nodelist = document.getElementsByTagName(elementTagName);
        for(int i = 0; i < nodelist.getLength(); i++) {
            Node node = nodelist.item(i);
            root.removeChild(node);
        }
    }
    
    private void checkdoc() {
        
        if(document == null) {
            DOMImplementation domImpl = builder.getDOMImplementation();
            document = domImpl.createDocument("","searchdata",null);
        }
        
        root = document.getDocumentElement();
        
    }
    
    public void read(File file) {
        
        try {
            document = builder.parse(file);
            root = document.getDocumentElement();
            
        } catch (SAXException | IOException ex) {
            Logger.getLogger(XmlSearchDataRW2.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    public void write(File file) {
        try {
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            
            DOMSource source = new DOMSource(document);
            FileOutputStream os = new FileOutputStream(file);
            StreamResult result = new StreamResult(os);
            transformer.transform(source, result);
            
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(XmlSearchDataRW2.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException | TransformerException ex) {
            Logger.getLogger(XmlSearchDataRW2.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
}
