package com.moex.asts.export;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.moex.asts.export.Description.TableInfo;

public class Settings {

    final Map<String, String> parameters;

    final Map<String, TableInfo> description;

    Settings(Map<String, String> parameters, Map<String, TableInfo> description) {
        if (parameters == null)
            this.parameters = Collections.emptyMap();
        else
            this.parameters = Collections.unmodifiableMap(parameters);
        if (description == null)
            this.description = Collections.emptyMap();
        else
            this.description = Collections.unmodifiableMap(description);
    }

    public Map<String, String> parameters() {
        return parameters;
    }

    private static File[] getSourceFiles(String names) throws IOException {
        List<File> files = new ArrayList<>();
        for (String name : names.split(File.pathSeparator)) {
            File file = new File(name);
            if (!file.exists())
                throw new IOException("'" + file
                        + "' file does not exist");
            if (!file.canRead())
                throw new IOException("'" + file
                        + "' file is not readable");
            files.add(file);
        }
        return files.toArray(new File[files.size()]);
    }

    public static Settings parse(String filename) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        Map<String, String> connection = null;
        Map<String, TableInfo> description = null;

        File[] sources = getSourceFiles(filename);
        for (File source : sources) {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(source);
            Element root = document.getDocumentElement();

            Element element = XmlUtil.getFirstChild(root, "connection");
            if (element != null)
                connection = XmlUtil.loadStringMap(element.getElementsByTagName("param"));

            element = XmlUtil.getFirstChild(root, "tables");
            if (element != null)
                description = Description.parse(element);
        }

        if (connection == null)
            throw new IOException("No 'connection' configured");
        if (description == null)
            throw new IOException("No 'tables' configured");
        return new Settings(connection, description);
    }

}
