/*
 * blancoCsv Copyright (C) 2005 Tosiki Iga
 * 
 * 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.csv.expand;

import java.io.File;

import blanco.commons.util.BlancoJavaSourceUtil;
import blanco.commons.util.BlancoNameAdjuster;
import blanco.csv.resourcebundle.BlancoCsvDotNetResourceBundle;
import blanco.csv.resourcebundle.BlancoCsvWriterDotNetResourceBundle;
import blanco.csv.valueobject.BlancoCsvFieldStructureDotNet;
import blanco.csv.valueobject.BlancoCsvStructureDotNet;
import blanco.ig.expander.ClassExpander;
import blanco.ig.expander.IgType;
import blanco.ig.expander.IgValue;
import blanco.ig.expander.field.FieldExpander;
import blanco.ig.expander.implementor.IgStatement;
import blanco.ig.expander.method.IgConstructor;
import blanco.ig.expander.method.MethodExpander;

public class BlancoCsvExpandWriterDotNet {
    final BlancoCsvDotNetResourceBundle bundle = new BlancoCsvDotNetResourceBundle();

    final BlancoCsvWriterDotNetResourceBundle writerBundle = new BlancoCsvWriterDotNetResourceBundle();

    public void expand(final BlancoCsvStructureDotNet processStructure,
            final File directoryTarget) {
        final String className = BlancoNameAdjuster
                .toClassName(processStructure.getFileDefinitionId())
                + writerBundle.getClassNameSuffix();
        final ClassExpander classExpander = new ClassExpander(new IgType(
                processStructure.getPackageName()
                        + writerBundle.getPackagePrefix(), className)) {
            protected void expandClassStruct() {
                addImport(new IgType(processStructure.getRuntimePackage()
                        + writerBundle.getAddusingtype01Suffix()));
                // 常にSystem名前空間はusingします。
                addImport(new IgType("System.String"));
                addFileComment(writerBundle.getFilecomment());

                getJavaDoc()
                        .addLine(
                                writerBundle
                                        .getClasscomment01(processStructure
                                                .getFileDefinitionId()
                                                + (processStructure
                                                        .getFileDescription() == null ? ""
                                                        : "/"
                                                                + processStructure
                                                                        .getFileDescription())));
                getJavaDoc().addLine(writerBundle.getClasscomment02());
                if (processStructure.getEncoding() == null) {
                    getJavaDoc()
                            .addLine(writerBundle.getClasscomment03Case01());
                } else {
                    getJavaDoc().addLine(
                            writerBundle
                                    .getClasscomment03Case02(processStructure
                                            .getEncoding()));
                }
                getJavaDoc().addLine(writerBundle.getClasscomment04());

                final FieldExpander field1 = new FieldExpander(new IgType(
                        writerBundle.getFieldWriterType()), writerBundle
                        .getFieldWriterName());
                field1.getJavaDoc().addLine(
                        writerBundle.getFieldWriterJavadoc01());
                field1.getJavaDoc().addLine(
                        writerBundle.getFieldWriterJavadoc02());
                addField(field1);

                final FieldExpander field2 = new FieldExpander(new IgType(
                        writerBundle.getFieldLineCounterType()), writerBundle
                        .getFieldLineCounterName());
                field2.getJavaDoc().addLine(
                        writerBundle.getFieldLineCounterJavadoc01());
                field2.getJavaDoc().addLine(
                        writerBundle.getFieldLineCounterJavadoc02());
                field2.setDefaultStatement(new IgStatement(writerBundle
                        .getFieldLineCounterDefault()));
                addField(field2);

                // 「書式」対応
                for (int indexField = 0; indexField < processStructure
                        .getListField().size(); indexField++) {
                    final BlancoCsvFieldStructureDotNet field = (BlancoCsvFieldStructureDotNet) processStructure
                            .getListField().get(indexField);

                    if (field.getType().equals("System.DateTime")) {
                        final FieldExpander field3 = new FieldExpander(
                                new IgType("string"), writerBundle
                                        .getFieldSimpleDateFormatNamePrefix()
                                        + BlancoNameAdjuster.toClassName(field
                                                .getName()));
                        field3
                                .getJavaDoc()
                                .addLine(
                                        writerBundle
                                                .getFieldSimpleDateFormatJavadoc01(field
                                                        .getName()));
                        field3.getJavaDoc().addLine(
                                writerBundle
                                        .getFieldSimpleDateFormatJavadoc02());
                        addField(field3);
                    }
                }

                addMethod(new IgConstructor(className) {
                    // メソッドのシグニチャ指定
                    public void setupSignature() {
                        getJavaDoc().addLine(
                                writerBundle.getConstructor01Javadoc01());
                        getJavaDoc().addLine(
                                writerBundle.getConstructor01Javadoc02());
                        getJavaDoc().addParameter("arg",
                                writerBundle.getConstructor01Arg01Javadoc01());
                        addArgument(new IgValue(new IgType(writerBundle
                                .getConstructor01Arg01Type()), "arg"));
                    }

                    // メソッドの実装
                    public void implement() {
                        getData().addLine("fWriter = arg;");

                        // 「書式」対応
                        for (int indexField = 0; indexField < processStructure
                                .getListField().size(); indexField++) {
                            final BlancoCsvFieldStructureDotNet field = (BlancoCsvFieldStructureDotNet) processStructure
                                    .getListField().get(indexField);

                            if (field.getType().equals("System.DateTime")) {
                                getData()
                                        .addLine(
                                                "fSimpleDateFormat"
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + " = "
                                                        + (field.getFormat() == null ? "\"yyyy/MM/dd\""
                                                                : "\""
                                                                        + field
                                                                                .getFormat()
                                                                        + "\"")
                                                        + ";");
                            }
                        }
                    }
                });

                if (processStructure.getTitleRow().equals("title with quote")
                        || processStructure.getTitleRow().equals(
                                "title without quote")) {
                    addMethod(new MethodExpander("writeTitle") {
                        public void setupSignature() {
                            getJavaDoc().addLine(
                                    writerBundle.getWritetitleJavadoc01());
                            getJavaDoc().addLine(
                                    writerBundle.getWritetitleJavadoc02());
                            if (processStructure.getTitleRow().equals(
                                    "title with quote")) {
                                getJavaDoc().addLine(
                                        writerBundle.getWritetitleJavadoc03());
                            }
                        }

                        public void implement() {
                            for (int indexField = 0; indexField < processStructure
                                    .getListField().size(); indexField++) {
                                final BlancoCsvFieldStructureDotNet field = (BlancoCsvFieldStructureDotNet) processStructure
                                        .getListField().get(indexField);
                                final String delimiter = (indexField != 0 ? processStructure
                                        .getDelimiter()
                                        : "");
                                final String quote = (processStructure
                                        .getTitleRow().equals(
                                                "title with quote") ? BlancoJavaSourceUtil
                                        .escapeStringAsJavaSource("\"")
                                        : "");
                                getData()
                                        .addLine(
                                                "fWriter.Write(\""
                                                        + delimiter
                                                        + quote
                                                        + BlancoJavaSourceUtil
                                                                .escapeStringAsJavaSource(field
                                                                        .getDescription())
                                                        + quote + "\");");
                            }
                            getData().addLine("fWriter.WriteLine();");
                        }
                    });
                }

                final String recordClassName = processStructure
                        .getPackageName()
                        + ".record."
                        + BlancoNameAdjuster.toClassName(processStructure
                                .getFileDefinitionId()) + "CsvRecord";

                addMethod(new MethodExpander("WriteRecord") {
                    // メソッドのシグニチャ指定
                    public void setupSignature() {
                        getJavaDoc().addLine(
                                writerBundle.getWriterecordJavadoc01());
                        getJavaDoc().addLine(
                                writerBundle.getWriterecordJavadoc02());
                        getJavaDoc().addParameter("record",
                                writerBundle.getWriterecordArg01Javadoc());
                        addArgument(new IgValue(new IgType(recordClassName),
                                "record"));
                    }

                    // メソッドの実装
                    public void implement() {
                        getData().addLine("string writeToken = null;");
                        for (int indexField = 0; indexField < processStructure
                                .getListField().size(); indexField++) {
                            final BlancoCsvFieldStructureDotNet field = (BlancoCsvFieldStructureDotNet) processStructure
                                    .getListField().get(indexField);

                            if (indexField != 0) {
                                getData()
                                        .addLine(
                                                "fWriter.Write('"
                                                        + processStructure
                                                                .getDelimiter()
                                                        + "');");
                            }

                            getData().addLine("");
                            getData()
                                    .addLine(
                                            writerBundle
                                                    .getWriterecordLine01(
                                                            (field.getNo() == null ? ""
                                                                    : bundle
                                                                            .getFieldNo(field
                                                                                    .getNo())
                                                                            + " "),
                                                            field.getName()
                                                                    + (field
                                                                            .getDescription() == null ? ""
                                                                            : "/"
                                                                                    + field
                                                                                            .getDescription())));

                            if (field.getType().equals("string")
                                    || field.getType().equals("string(quote)")) {
                                if (field.getRequired()) {
                                    // 必須項目。
                                    getData().addLine(
                                            "if (record.Get"
                                                    + BlancoNameAdjuster
                                                            .toClassName(field
                                                                    .getName())
                                                    + "() == null) {");
                                    getData()
                                            .addLine(
                                                    "throw new BlancoCsvIOException(\""
                                                            + bundle
                                                                    .getCsvWriterErr004(getLocationString(
                                                                            indexField,
                                                                            field
                                                                                    .getNo(),
                                                                            field
                                                                                    .getName(),
                                                                            field
                                                                                    .getDescription()))
                                                            + "\");");
                                    getData().addLine("}");
                                    getData().addLine(
                                            "if (record.Get"
                                                    + BlancoNameAdjuster
                                                            .toClassName(field
                                                                    .getName())
                                                    + "().Length == 0) {");
                                    getData()
                                            .addLine(
                                                    "throw new BlancoCsvIOException(\""
                                                            + bundle
                                                                    .getCsvWriterErr005(getLocationString(
                                                                            indexField,
                                                                            field
                                                                                    .getNo(),
                                                                            field
                                                                                    .getName(),
                                                                            field
                                                                                    .getDescription()))
                                                            + "\");");
                                    getData().addLine("}");
                                    getData().addLine(
                                            "writeToken = record.Get"
                                                    + BlancoNameAdjuster
                                                            .toClassName(field
                                                                    .getName())
                                                    + "();");
                                } else {
                                    // 任意項目であるので nullは長さ0の文字列へと読み替えます。
                                    getData()
                                            .addLine(
                                                    "// 任意項目で文字列の項目に nullまたは長さ0の文字列が与えられた場合には、いずれも値が入っていないものとみなします。");
                                    getData().addLine("// この場合には長さチェックは行いません。");
                                    getData()
                                            .addLine(
                                                    "writeToken = record.Get"
                                                            + BlancoNameAdjuster
                                                                    .toClassName(field
                                                                            .getName())
                                                            + "() == null ? \"\" : record.Get"
                                                            + BlancoNameAdjuster
                                                                    .toClassName(field
                                                                            .getName())
                                                            + "();");

                                    // if文が開始した状態のままにします。
                                    getData().addLine(
                                            "if (writeToken.Length > 0) {");
                                }
                            } else if (field.getType().equals("int")
                                    || field.getType().equals("long")
                                    || field.getType().equals("decimal")
                                    || field.getType()
                                            .equals("System.DateTime")) {
                                if (field.getRequired()) {
                                    // 必須項目。
                                    if (field.getType().equals(
                                            "System.DateTime") == false) {
                                        getData()
                                                .addLine(
                                                        "writeToken = record.Get"
                                                                + BlancoNameAdjuster
                                                                        .toClassName(field
                                                                                .getName())
                                                                + "().ToString();");
                                    } else {
                                        getData()
                                                .addLine(
                                                        "writeToken = record.Get"
                                                                + BlancoNameAdjuster
                                                                        .toClassName(field
                                                                                .getName())
                                                                + "().ToString(fSimpleDateFormat"
                                                                + BlancoNameAdjuster
                                                                        .toClassName(field
                                                                                .getName())
                                                                + ");");
                                    }
                                } else {
                                    // 任意項目。
                                    getData().addLine(
                                            "if (record.Get"
                                                    + BlancoNameAdjuster
                                                            .toClassName(field
                                                                    .getName())
                                                    + "() == "
                                                    + field.getType()
                                                    + ".MinValue) {");
                                    getData().addLine("writeToken = \"\";");
                                    getData().addLine("} else {");
                                    // if文が開始した状態のままにします。

                                    if (field.getType().equals(
                                            "System.DateTime") == false) {
                                        getData()
                                                .addLine(
                                                        "writeToken = record.Get"
                                                                + BlancoNameAdjuster
                                                                        .toClassName(field
                                                                                .getName())
                                                                + "().ToString();");
                                    } else {
                                        getData()
                                                .addLine(
                                                        "writeToken = record.Get"
                                                                + BlancoNameAdjuster
                                                                        .toClassName(field
                                                                                .getName())
                                                                + "().ToString(fSimpleDateFormat"
                                                                + BlancoNameAdjuster
                                                                        .toClassName(field
                                                                                .getName())
                                                                + ");");
                                    }
                                }
                            } else {
                                getData().addLine(
                                        bundle.getNotSupportedType(field
                                                .getType()));
                            }

                            if (field.getRequired()) {
                                // 必須項目。
                                if (field.getType().equals("string")
                                        || field.getType().equals(
                                                "string(quote)")) {
                                    getData().addLine(
                                            "if (writeToken == null) {");
                                    getData()
                                            .addLine(
                                                    "throw new BlancoCsvIOException(\""
                                                            + bundle
                                                                    .getCsvWriterErr004(getLocationString(
                                                                            indexField,
                                                                            field
                                                                                    .getNo(),
                                                                            field
                                                                                    .getName(),
                                                                            field
                                                                                    .getDescription()))
                                                            + "\");");
                                    getData().addLine("}");
                                } else if (field.getType().equals("int")
                                        || field.getType().equals("long")
                                        || field.getType().equals("decimal")
                                        || field.getType().equals(
                                                "System.DateTime")) {
                                    getData().addLine(
                                            "if (record.Get"
                                                    + BlancoNameAdjuster
                                                            .toClassName(field
                                                                    .getName())
                                                    + "() == "
                                                    + field.getType()
                                                    + ".MinValue) {");
                                    getData()
                                            .addLine(
                                                    "throw new BlancoCsvIOException(\""
                                                            + bundle
                                                                    .getCsvWriterErr006(getLocationString(
                                                                            indexField,
                                                                            field
                                                                                    .getNo(),
                                                                            field
                                                                                    .getName(),
                                                                            field
                                                                                    .getDescription()))
                                                            + "\");");
                                    getData().addLine("}");
                                }
                            }

                            if (field.getMinLength() != null) {
                                // 型の利用を追加します。
                                addUsingType(new IgType(processStructure
                                        .getRuntimePackage()
                                        + ".util.BlancoCsvRuntimeUtil"));

                                getData().addLine(
                                        "if (BlancoCsvRuntimeUtil.GetBytes(writeToken"
                                                + ").Length < "
                                                + field.getMinLength() + ") {");
                                getData()
                                        .addLine(
                                                "throw new BlancoCsvIOException(\""
                                                        + bundle
                                                                .getCsvWriterErr001(
                                                                        getLocationString(
                                                                                indexField,
                                                                                field
                                                                                        .getNo(),
                                                                                field
                                                                                        .getName(),
                                                                                field
                                                                                        .getDescription()),
                                                                        field
                                                                                .getMinLength())
                                                        + "\");");
                                getData().addLine("}");
                            }
                            if (field.getMaxLength() != null) {
                                // 型の利用を追加します。
                                addUsingType(new IgType(processStructure
                                        .getRuntimePackage()
                                        + ".util.BlancoCsvRuntimeUtil"));

                                getData().addLine(
                                        "if (BlancoCsvRuntimeUtil.GetBytes(writeToken"
                                                + ").Length > "
                                                + field.getMaxLength() + ") {");
                                getData()
                                        .addLine(
                                                "throw new BlancoCsvIOException(\""
                                                        + bundle
                                                                .getCsvWriterErr002(
                                                                        getLocationString(
                                                                                indexField,
                                                                                field
                                                                                        .getNo(),
                                                                                field
                                                                                        .getName(),
                                                                                field
                                                                                        .getDescription()),
                                                                        field
                                                                                .getMaxLength())
                                                        + "\");");
                                getData().addLine("}");
                            }

                            if (field.getRequired()) {
                            } else {
                                // 任意項目はカッコが開きっぱなしであるので、ここで閉じます。
                                getData().addLine("}");
                            }

                            if (field.getType().equals("string")) {
                                getData().addLine(
                                        "if (writeToken.IndexOf(\""
                                                + processStructure
                                                        .getDelimiter()
                                                + "\") >= 0) {");
                                getData()
                                        .addLine(
                                                "throw new BlancoCsvIOException(\""
                                                        + bundle
                                                                .getCsvWriterErr003(
                                                                        getLocationString(
                                                                                indexField,
                                                                                field
                                                                                        .getNo(),
                                                                                field
                                                                                        .getName(),
                                                                                field
                                                                                        .getDescription()),
                                                                        processStructure
                                                                                .getDelimiter())
                                                        + "\");");
                                getData().addLine("}");
                                getData().addLine("fWriter.Write(writeToken);");
                            } else if (field.getType().equals("string(quote)")) {
                                // 型の利用を追加します。
                                addUsingType(new IgType(processStructure
                                        .getRuntimePackage()
                                        + ".util.BlancoCsvRuntimeUtil"));

                                getData().addLine(
                                        writerBundle.getWriterecordLine02());
                                getData()
                                        .addLine(
                                                "fWriter.Write(BlancoCsvRuntimeUtil.GetTokenWithQuote(writeToken));");
                            } else {
                                getData().addLine("fWriter.Write(writeToken);");
                            }
                        }
                        getData().addLine("");
                        getData().addLine(writerBundle.getWriterecordLine03());
                        getData().addLine("fWriter.WriteLine();");
                        getData().addLine("fLineCounter++;");
                    }
                });

                addMethod(new MethodExpander("GetLineCounter") {
                    // メソッドのシグニチャ指定
                    public void setupSignature() {
                        getJavaDoc().addLine("現在処理中の行カウンタを返します。");
                        getJavaDoc().addReturn("現在処理中の行カウンタ。");
                        setReturnType(new IgType("long"));
                    }

                    // メソッドの実装
                    public void implement() {
                        getData().addLine("return fLineCounter;");
                    }
                });

                addMethod(new MethodExpander("Flush") {
                    // メソッドのシグニチャ指定
                    public void setupSignature() {
                        getJavaDoc().addLine(writerBundle.getFlushJavadoc01());
                        getJavaDoc().addLine(writerBundle.getFlushJavadoc02());
                    }

                    // メソッドの実装
                    public void implement() {
                        getData().addLine("fWriter.Flush();");
                    }
                });

                addMethod(new MethodExpander("Close") {
                    // メソッドのシグニチャ指定
                    public void setupSignature() {
                        getJavaDoc().addLine(writerBundle.getCloseJavadoc01());
                        getJavaDoc().addLine(writerBundle.getCloseJavadoc02());
                    }

                    // メソッドの実装
                    public void implement() {
                        getData().addLine("fWriter.Close();");
                    }
                });
            }
        };

        ClassExpander.generateCsSource(classExpander, directoryTarget);
    }

    private String getLocationString(int indexField, String fieldNo,
            String fieldName, String fieldDescription) {
        return writerBundle.getGetlocationstringLine01("" + (indexField + 1),
                (fieldNo == null ? "" : bundle.getFieldNo(fieldNo) + " "),
                fieldName
                        + (fieldDescription == null ? "" : "/"
                                + fieldDescription));
    }
}
