/*
 * 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.fixedlength.expand;

import java.io.File;

import blanco.commons.util.BlancoNameAdjuster;
import blanco.fixedlength.resourcebundle.BlancoFixedLengthDotNetResourceBundle;
import blanco.fixedlength.resourcebundle.BlancoFixedLengthWriterDotNetResourceBundle;
import blanco.fixedlength.valueobject.BlancoFixedLengthFieldStructureDotNet;
import blanco.fixedlength.valueobject.BlancoFixedLengthStructureDotNet;
import blanco.ig.expander.ClassExpander;
import blanco.ig.expander.Type;
import blanco.ig.expander.Value;
import blanco.ig.expander.field.FieldExpander;
import blanco.ig.expander.implementor.Statement;
import blanco.ig.expander.method.Constructor;
import blanco.ig.expander.method.MethodExpander;

public class BlancoFixedLengthExpandWriterDotNet {
    final BlancoFixedLengthDotNetResourceBundle bundle = new BlancoFixedLengthDotNetResourceBundle();

    final BlancoFixedLengthWriterDotNetResourceBundle writerBundle = new BlancoFixedLengthWriterDotNetResourceBundle();

    public void expand(final BlancoFixedLengthStructureDotNet processStructure,
            final File directoryTarget) {
        final String className = BlancoNameAdjuster
                .toClassName(processStructure.getFileDefinitionId())
                + writerBundle.getClassNameSuffix();
        final Type typeIOException = new Type(processStructure
                .getRuntimePackage()
                + writerBundle.getAddusingtype01Suffix());
        final ClassExpander classExpander = new ClassExpander(new Type(
                processStructure.getPackageName()
                        + writerBundle.getPackagePrefix(), className)) {
            protected void expandClassStruct() {
                addImport(typeIOException);
                addFileComment(writerBundle.getFilecomment());

                getJavaDoc()
                        .addLine(
                                writerBundle
                                        .getClasscomment01(processStructure
                                                .getFileDefinitionId()
                                                + (processStructure
                                                        .getFileDescription() == null ? ""
                                                        : "/"
                                                                + processStructure
                                                                        .getFileDescription())));
                getJavaDoc().addLine(writerBundle.getClasscomment02());
                getJavaDoc().addLine(writerBundle.getClasscomment03Case01());
                getJavaDoc().addLine(writerBundle.getClasscomment04());

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

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

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

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

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

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

                        // 「書式」対応
                        for (int indexField = 0; indexField < processStructure
                                .getListField().size(); indexField++) {
                            final BlancoFixedLengthFieldStructureDotNet field = (BlancoFixedLengthFieldStructureDotNet) 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()
                                                                        + "\"")
                                                        + ";");
                            }
                        }
                    }
                });

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

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

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

                            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")) {
                                // 任意項目であるので nullは長さ0の文字列へと読み替えます。
                                getData()
                                        .addLine(
                                                "// 任意項目で文字列の項目に nullまたは長さ0の文字列が与えられた場合には、いずれも値が入っていないものとみなします。");
                                getData().addLine("// この場合には長さチェックは行いません。");
                                getData()
                                        .addLine(
                                                "writeToken = record.Get"
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + "() == null ? \"\" : record.Get"
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + "();");
                            } else if (field.getType().equals("int")
                                    || field.getType().equals("long")) {
                                // 任意項目。
                                getData().addLine(
                                        "writeToken = record.Get"
                                                + BlancoNameAdjuster
                                                        .toClassName(field
                                                                .getName())
                                                + "().ToString();");
                            } else if (field.getType()
                                    .equals("System.DateTime")) {
                                getData().addLine(
                                        "if (record.Get"
                                                + BlancoNameAdjuster
                                                        .toClassName(field
                                                                .getName())
                                                + "() == null) {");
                                getData()
                                        .addLine(
                                                "throw new BlancoFixedLengthIOException(\""
                                                        + bundle
                                                                .getCsvWriterErr011(getLocationString(
                                                                        indexField,
                                                                        field
                                                                                .getNo(),
                                                                        field
                                                                                .getName(),
                                                                        field
                                                                                .getDescription()))
                                                        + "\");");
                                getData().addLine("}");
                                getData()
                                        .addLine(
                                                "writeToken = record.Get"
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + "().ToString(fSimpleDateFormat"
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + ");");
                            } else if (field.getType().equals("decimal")) {
                                getData()
                                        .addLine(
                                                "writeToken = record.Get"
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + "() == null ? \"\" : record.Get"
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + "().ToString();");
                            } else {
                                getData().addLine(
                                        bundle.getNotSupportedType(field
                                                .getType()));
                                getData().addLine("writeToken = \"\";");
                            }

                            String strPadDirection = "Right";
                            if (field.getType().equals("int")
                                    || field.getType().equals("long")
                                    || field.getType().equals("decimal")) {
                                strPadDirection = "Left";
                            }

                            addUsingType(new Type(processStructure
                                    .getRuntimePackage()
                                    + ".util.BlancoFixedLengthRuntimeUtil"));
                            getData().addLine("// 指定の長さまでパディングします。");
                            getData().addLine(
                                    "writeToken = BlancoFixedLengthRuntimeUtil.Pad"
                                            + strPadDirection + "(writeToken, "
                                            + field.getLength() + ", ' ');");

                            getData().addLine(
                                    "if (BlancoFixedLengthRuntimeUtil.GetBytes(writeToken).Length < "
                                            + field.getLength() + ") {");
                            getData()
                                    .addLine(
                                            "throw new BlancoFixedLengthIOException(\""
                                                    + bundle
                                                            .getCsvWriterErr001(
                                                                    getLocationString(
                                                                            indexField,
                                                                            field
                                                                                    .getNo(),
                                                                            field
                                                                                    .getName(),
                                                                            field
                                                                                    .getDescription()),
                                                                    field
                                                                            .getLength())
                                                    + "\");");
                            getData().addLine("}");

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

                            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 Type("long"));
                    }

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

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

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

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

                    // メソッドの実装
                    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));
    }
}
