package blanco.db.task;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

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

import org.xml.sax.SAXException;

import blanco.commons.util.BlancoStringUtil;
import blanco.db.BlancoDbDotNetConstants;
import blanco.db.BlancoDbMeta2XmlDotNet;
import blanco.db.BlancoDbXml2CsClassDotNet;
import blanco.db.common.BlancoDbTableMeta2Xml;
import blanco.db.common.stringgroup.BlancoDbExecuteSqlStringGroup;
import blanco.db.common.valueobject.BlancoDbSetting;
import blanco.db.resourcebundle.BlancoDbDotNetResourceBundle;
import blanco.db.stringgroup.BlancoDbDotNetDataAccessTypeStringGroup;
import blanco.db.task.valueobject.BlancoDbDotNetProcessInput;
import blanco.dbmetadata.valueobject.BlancoDbMetaDataColumnStructure;

public class BlancoDbDotNetProcessImpl implements BlancoDbDotNetProcess {
    /**
     * リソースバンドルアクセサオブジェクトを記憶します。
     */
    private final BlancoDbDotNetResourceBundle fBundle = new BlancoDbDotNetResourceBundle();

    public int execute(final BlancoDbDotNetProcessInput input)
            throws IOException, IllegalArgumentException {
        System.out.println("- " + BlancoDbDotNetConstants.PRODUCT_NAME + " ("
                + BlancoDbDotNetConstants.VERSION + ")");

        try {
            System.out.println("db: begin.");
            final long startMills = System.currentTimeMillis();

            final File blancoTmpDbTableDirectory = new File(input.getTmpdir()
                    + BlancoDbDotNetConstants.TARGET_SUBDIRECTORY + "/table");
            final File blancoTmpDbSqlDirectory = new File(input.getTmpdir()
                    + BlancoDbDotNetConstants.TARGET_SUBDIRECTORY + "/sql");
            blancoTmpDbTableDirectory.mkdirs();
            blancoTmpDbSqlDirectory.mkdirs();

            final BlancoDbSetting dbSetting = new BlancoDbSetting();
            dbSetting.setTargetDir(input.getTargetdir());
            dbSetting.setBasePackage(input.getBasepackage());
            dbSetting.setRuntimePackage(input.getRuntimepackage());

            dbSetting.setJdbcdriver(input.getJdbcdriver());
            dbSetting.setJdbcurl(input.getJdbcurl());
            dbSetting.setJdbcuser(input.getJdbcuser());
            dbSetting.setJdbcpassword(input.getJdbcpassword());
            if (BlancoStringUtil.null2Blank(input.getJdbcdriverfile()).length() > 0) {
                dbSetting.setJdbcdriverfile(input.getJdbcdriverfile());
            }
            dbSetting.setEncoding(input.getEncoding());

            if (input.getLog()) {
                dbSetting.setLogging(true);
            }
            if (BlancoStringUtil.null2Blank(input.getStatementtimeout())
                    .length() > 0) {
                try {
                    dbSetting.setStatementTimeout(Integer.parseInt(input
                            .getStatementtimeout()));
                } catch (NumberFormatException ex) {
                    throw new IllegalArgumentException(
                            "ステートメントタイムアウト値として指定された値["
                                    + input.getStatementtimeout()
                                    + "]は数値として解析できませんでした。処理中断します。:"
                                    + ex.toString());
                }
            }
            dbSetting.setExecuteSql(new BlancoDbExecuteSqlStringGroup()
                    .convertToInt(input.getExecutesql()));
            if (dbSetting.getExecuteSql() == BlancoDbExecuteSqlStringGroup.NOT_DEFINED) {
                throw new IllegalArgumentException("executesqlとして不正な値("
                        + input.getExecutesql() + ")が与えられた。");
            }

            int dataAccessType = new BlancoDbDotNetDataAccessTypeStringGroup()
                    .convertToInt(input.getDataaccess());
            if (dataAccessType == BlancoDbDotNetDataAccessTypeStringGroup.NOT_DEFINED) {
                throw new IllegalArgumentException("dacaaccessとして不正な値("
                        + input.getDataaccess() + ")が与えられました。");
            }

            if (input.getSchema() != null) {
                // スキーマ名を指定。
                dbSetting.setSchema(input.getSchema());
            }

            if (input.getTable()) {
                // 単一表アクセサを自動生成
                final BlancoDbTableMeta2Xml tableMeta2Xml = new BlancoDbTableMeta2Xml() {
                    public boolean progress(int progressCurrent,
                            int progressTotal, String progressItem) {
                        // 常にtrueを返します。
                        return true;
                    }

                    protected boolean isSkipTypeForSimpleTable(
                            final BlancoDbMetaDataColumnStructure columnStructure) {
                        // DotNet版ではバイナリ型やlongvarcharを通常の表アクセスと同時に扱うことができます。
                        return false;
                    }
                };
                tableMeta2Xml.setFormatSql(true);
                tableMeta2Xml.process(dbSetting, blancoTmpDbTableDirectory);

                // XMLファイルを元にR/Oマッピングを自動生成
                final BlancoDbXml2CsClassDotNet generator = new BlancoDbXml2CsClassDotNet() {
                    public boolean progress(int progressCurrent,
                            int progressTotal, String progressItem) {
                        // 常にtrueを返します。
                        return true;
                    }
                };
                if (input.getLog()) {
                    dbSetting.setLogging(true);
                }
                generator.process(dbSetting, blancoTmpDbTableDirectory,
                        dataAccessType);
            }

            if (input.getSql()) {
                final File fileMetadir = new File(input.getMetadir());
                if (fileMetadir.exists() == false) {
                    throw new IllegalArgumentException(fBundle
                            .getAnttaskErr001(input.getMetadir()));
                }

                final BlancoDbMeta2XmlDotNet meta2Xml = new BlancoDbMeta2XmlDotNet();
                meta2Xml.setCacheMeta2Xml(input.getCache());
                meta2Xml.processDirectory(fileMetadir, blancoTmpDbSqlDirectory
                        .getAbsolutePath());

                // XMLファイルを元にR/Oマッピングを自動生成
                final BlancoDbXml2CsClassDotNet generator = new BlancoDbXml2CsClassDotNet() {
                    public boolean progress(int progressCurrent,
                            int progressTotal, String progressItem) {
                        // 常にtrueを返します。
                        return true;
                    }
                };
                if (input.getLog()) {
                    dbSetting.setLogging(true);
                }
                generator.process(dbSetting, blancoTmpDbSqlDirectory,
                        dataAccessType);
            }

            final long endMills = System.currentTimeMillis() - startMills;
            System.out.println("db: end: " + (endMills / 1000) + " sec.");
        } catch (SQLException e) {
            throw new IllegalArgumentException(fBundle.getTaskErr001()
                    + e.toString());
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException(fBundle.getTaskErr002()
                    + e.toString());
        } catch (SAXException e) {
            e.printStackTrace();
            throw new IllegalArgumentException(fBundle.getTaskErr003()
                    + e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException(fBundle.getTaskErr004()
                    + e.toString());
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            throw new IllegalArgumentException(fBundle.getTaskErr005()
                    + e.toString());
        } catch (TransformerException e) {
            e.printStackTrace();
            throw new IllegalArgumentException(fBundle.getTaskErr006()
                    + e.toString());
        }
        return 0;
    }

    /**
     * {@inheritDoc}
     */
    public boolean progress(final String argProgressMessage) {
        System.out.println(argProgressMessage);
        return false;
    }
}
