package usda.weru.mcrew.timeline;

import de.schlichtherle.truezip.file.TFile;

import java.math.BigInteger;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; 
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.TreeWalker;

import usda.weru.mcrew.XMLDoc;

/**
 * This class handles the configuration options attached to the timeline.
 *
 * @author jonathanhornbaker
 */
public class TimelineConfig {

    private static final Logger LOGGER = LogManager.getLogger(TimelineConfig.class);

    static int height = 10;
    static int width = 2;

    private static final String CONFIG_FILE = TFile.separator + "timeline" + TFile.separator + "timelineConfig.xml";

    /**
     * Driver function for initializing data contained within the timeline
     * config.
     */
    public static void initialize() {
        initData(System.getProperty("user.dir") + TFile.separator
                + "mcrew_cfg" + CONFIG_FILE);
    }

    /**
     * Reads in the timelineconfig file and stores it's data for access by other
     * timeline classes.
     *
     * @param docName
     */
    private static void initData(String docName) {
        Document doc = XMLDoc.getDocument(docName);
        if (doc != null) {
            doc.normalize();
        } else {
            return;
        }
        try {
            DocumentTraversal traversable = (DocumentTraversal) doc;
            TreeWalker walker = traversable.createTreeWalker(doc.getDocumentElement(), NodeFilter.SHOW_ALL, null, false);
            Node node = walker.firstChild();
            while (node != null) {
                String name = node.getNodeName();
                String nodeData = XMLDoc.getTextData(node);

                switch (name) {
                    case "height":
                        try {
                        height = Integer.parseInt(nodeData);
                    } catch (NumberFormatException nfe) {
                        LOGGER.warn("Failed to parse"
                                + "height value from TimelineConfig.  Using default.");
                    }
                    break;
                    default:
                }
                node = walker.nextSibling();
            }
        } catch (DOMException DOMEx) {
        }
    }

    /**
     * Essentially a least common multiple function.
     *
     * @param rot
     * @return
     */
    public static int getRotationYears(int[] rot) {
        BigInteger years = new BigInteger("1");
        BigInteger curr;
        for (int item : rot) {
            curr = new BigInteger("" + item);
            years = curr.multiply(years.divide(years.gcd(curr)));
        }
        return years.intValue();
    }
}
