/*
 * blancoDb
 * Copyright (C) 2004-2005 Yasuo Nakanishi
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 */
package blanco.db.alias.pool;

import java.io.File;
import java.io.IOException;

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.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import blanco.ig.generator.GeneratorSetting;

/**
 * @author Yasuo Nakanishi
 */
public class AliasLoader {
    private GeneratorSetting _setting = null;

    public AliasLoader(GeneratorSetting setting) {
        _setting = setting;
    }

    protected String getFilePath() {
        return _setting.getWorkDirectory() + "/AliasPool.xml";
    }

    public AliasPool load() throws SAXException, IOException,
            ParserConfigurationException {
        AliasPool result = new AliasPool();
        Alias alias;

        DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = dbfactory.newDocumentBuilder();

        File f = new File(getFilePath());

        if (f.exists()) {
            Document doc = builder.parse(f);
            Element root = doc.getDocumentElement();
            NodeList list = root.getChildNodes();
            Node node = null;

            int length = list.getLength();
            for (int i = 0; i < length; i++) {
                node = list.item(i);
                if (node.getNodeName().equals("Alias")) {
                    NamedNodeMap map = node.getAttributes();
                    alias = new Alias(map.getNamedItem("name").getNodeValue(),
                            map.getNamedItem("alias").getNodeValue());
                    result.addAlias(alias);
                }

            }
        }
        return result;
    }
}