/*
 * blanco Framework
 * Copyright (C) 2004-2009 IGA Tosiki
 * 
 * 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.jsf.db;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.xml.sax.SAXException;

import blanco.db.common.BlancoDbCommonConstants;
import blanco.db.common.util.BlancoDbXmlParser;
import blanco.db.common.valueobject.BlancoDbSqlInfoStructure;

public class BlancoJsfDbParser {
    public List<BlancoDbSqlInfoStructure> process(
            final File fileRootTmpDirectory) {
        List<BlancoDbSqlInfoStructure> result = new ArrayList<BlancoDbSqlInfoStructure>();

        final File fileTable = new File(fileRootTmpDirectory.getAbsolutePath()
                + BlancoDbCommonConstants.TARGET_SUBDIRECTORY + "/table");
        result.addAll(processDir(fileTable));

        final File fileSql = new File(fileRootTmpDirectory.getAbsolutePath()
                + BlancoDbCommonConstants.TARGET_SUBDIRECTORY + "/sql");
        result.addAll(processDir(fileSql));

        return result;
    }

    private List<BlancoDbSqlInfoStructure> processDir(final File fileDir) {
        List<BlancoDbSqlInfoStructure> result = new ArrayList<BlancoDbSqlInfoStructure>();

        final File[] files = fileDir.listFiles();
        if (files == null) {
            return result;
        }

        for (File item : files) {
            if (item.isDirectory()) {
                continue;
            }
            if (item.getName().endsWith(".xml") == false) {
                continue;
            }
            result.addAll(processSqlForm(item));
        }
        return result;
    }

    private final List<BlancoDbSqlInfoStructure> processSqlForm(
            final File fileSqlForm) {
        try {
            final List<BlancoDbSqlInfoStructure> structures = new BlancoDbXmlParser()
                    .parse(fileSqlForm);
            return structures;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
