/*
 * Copyright (C) 2023 favdb
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package storybook.tools.xml;

import api.shef.tools.LOG;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import storybook.model.hbn.entity.AbstractEntity;

/**
 * utility class for setting/getting values from Xml
 *
 * @author favdb
 */
public class XmlUtil {

	public XmlUtil() {

	}

	/**
	 * set a XML attribute to a String
	 *
	 * @param tab number of tabulations
	 * @param name
	 * @param value
	 *
	 * @return
	 */
	public static String setAttribute(int tab, String name, String value) {
		if (value == null) {
			return "";
		}
		StringBuilder t = new StringBuilder();
		if (tab == 0) {
			t.append(" ");
		} else {
			t.append("\n");
			for (int i = 0; i < tab; i++) {
				t.append("    ");
			}
		}
		return t.toString() + name + "=\"" + value.replace("\"", "''") + "\"" + " ";
	}

	public static String setAttribute(int tab, XmlKey.XK key, AbstractEntity value) {
		if (value == null) {
			return "";
		}
		return setAttribute(tab, key, value.getId());
	}

	public static String setAttribute(int tab, XmlKey.XK key, Timestamp value) {
		if (value == null) {
			return "";
		}
		return setAttribute(tab, key.toString(), value.toString());
	}

	public static String setAttribute(int tab, XmlKey.XK key, String value) {
		return setAttribute(tab, key.toString(), value);
	}

	public static String setAttribute(int tab, XmlKey.XK key, boolean value) {
		return setAttribute(tab, key.toString(), (value ? "1" : "0"));
	}

	public static String setAttribute(int tab, XmlKey.XK key, Long value) {
		if (value == null) {
			return "";
		}
		return setAttribute(tab, key.toString(), value.toString());
	}

	public static String setAttribute(int tab, XmlKey.XK key, Integer value) {
		if (value == null) {
			return "";
		}
		return setAttribute(tab, key.toString(), value.toString());
	}

	public static String setAttribute(XmlKey.XK key, String value) {
		return setAttribute(key.toString().toLowerCase(), value);
	}

	public static String setAttribute(String name, String value) {
		if (value == null) {
			return (name.toLowerCase() + "=\"\"\n");
		}
		return (name.toLowerCase() + "=\"" + value.replace("\"", "''") + "\"\n");
	}

	public static String getString(Node node, XmlKey.XK key) {
		return getString(node, key.toString().toLowerCase());
	}

	public static String getString(Node node, String n) {
		Element e = (Element) node;
		return (e.getAttribute(n).trim());
	}

	public static boolean getBoolean(Node node, XmlKey.XK key) {
		return getBoolean(node, key.toString().toLowerCase());
	}

	public static boolean getBoolean(Node node, String n) {
		String s = getString(node, n);
		return (s.equals("yes") || s.equals("true") || s.equals("1"));
	}

	public static Long getLong(Node node, String n) {
		String x = getString(node, n);
		if (x.isEmpty() || "null".equals(x)) {
			return (null);
		}
		return (Long.valueOf(x));
	}

	public static Long getLong(Node node, XmlKey.XK key) {
		return getLong(node, key.toString().toLowerCase());
	}

	public static Integer getInteger(Node node, XmlKey.XK key) {
		return getInteger(node, key.toString().toLowerCase());
	}

	public static Integer getInteger(Node node, String n) {
		String x = getString(node, n);
		if (x.isEmpty() || "null".equals(x)) {
			return (null);
		}
		return (Integer.valueOf(x));
	}

	public static Timestamp getTimestamp(Node node, XmlKey.XK key) {
		return XmlUtil.getTimestamp(node, key.toString().toLowerCase());
	}

	public static Timestamp getTimestamp(Node node, String n) {
		String ts = getString(node, n);
		if (!ts.isEmpty()) {
			return (Timestamp.valueOf(ts));
		}
		return ((Timestamp) null);
	}

	public static String getText(Node node, XmlKey.XK key) {
		return getText(node, key.toString().toLowerCase());
	}

	public static String getText(Node node, String n) {
		NodeList t = node.getChildNodes();
		if (t.getLength() > 0) {
			for (int i = 0; i < t.getLength(); i++) {
				if (t.item(i).getNodeName().equals(n)) {
					return (t.item(i).getTextContent().trim());
				}
			}
		}
		return ("");
	}

	public static List<String> getList(Node node, XmlKey.XK key) {
		return getList(node, key.toString().toLowerCase());
	}

	public static List<String> getList(Node node, String n) {
		NodeList t = node.getChildNodes();
		List<String> list = new ArrayList<>();
		if (t.getLength() > 0) {
			for (int i = 0; i < t.getLength(); i++) {
				if (t.item(i).getNodeName().equals(n)) {
					list.add(t.item(i).getTextContent().trim());
				}
			}
		}
		return (list);
	}

	public static String format(String xmlString) {
		try {
			InputSource src = new InputSource(new StringReader(xmlString));
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = builder.parse(src);

			TransformerFactory factory = TransformerFactory.newInstance();
			factory.setAttribute("indent-number", 3);
			Transformer trans = factory.newTransformer();
			trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			trans.setOutputProperty(OutputKeys.INDENT, "yes");

			Writer out = new StringWriter();
			trans.transform(new DOMSource(document), new StreamResult(out));
			return out.toString();
		} catch (IOException
		   | IllegalArgumentException
		   | ParserConfigurationException
		   | TransformerException
		   | SAXException e) {
			LOG.err("Error occurs when pretty-printing xml:\n" + xmlString, e);
			return xmlString;
		}
	}

}
