/*
 * blanco Framework
 * Copyright (C) 2004-2006 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.logmessage.task;

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

import javax.xml.transform.TransformerException;

import blanco.logmessage.BlancoLogMessageConstants;
import blanco.logmessage.BlancoLogMessageMeta2Xml;
import blanco.logmessage.BlancoLogMessageXml2SourceFile;
import blanco.logmessage.message.BlancoLogMessageMessage;
import blanco.logmessage.task.valueobject.BlancoLogMessageProcessInput;

public class BlancoLogMessageProcessImpl implements BlancoLogMessageProcess {
    /**
     * メッセージ。
     */
    private final BlancoLogMessageMessage fMsg = new BlancoLogMessageMessage();

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

        try {
            final File fileMetadir = new File(input.getMetadir());
            if (fileMetadir.exists() == false) {
                throw new IllegalArgumentException(fMsg.getMbmsga01(input
                        .getMetadir()));
            }

            // テンポラリディレクトリを作成。
            new File(input.getTmpdir()
                    + BlancoLogMessageConstants.TARGET_SUBDIRECTORY).mkdirs();

            // 指定されたメタディレクトリを処理します。
            new BlancoLogMessageMeta2Xml().processDirectory(fileMetadir, input
                    .getTmpdir()
                    + BlancoLogMessageConstants.TARGET_SUBDIRECTORY);

            // XML化された中間ファイルからソースコードを生成
            final File[] fileMeta2 = new File(input.getTmpdir()
                    + BlancoLogMessageConstants.TARGET_SUBDIRECTORY)
                    .listFiles();
            for (int index = 0; index < fileMeta2.length; index++) {
                if (fileMeta2[index].getName().endsWith(".xml") == false) {
                    continue;
                }

                final BlancoLogMessageXml2SourceFile xml2sourceFile = new BlancoLogMessageXml2SourceFile();
                xml2sourceFile.setTargetLogger(input.getTargetLogger());
                xml2sourceFile.process(fileMeta2[index], input.getTargetlang(),
                        new File(input.getTargetdir()));
            }

            return BlancoLogMessageBatchProcess.END_SUCCESS;
        } catch (TransformerException ex) {
            throw new IOException("XML変換の過程で例外が発生しました: " + ex.toString());
        }
    }
}
