/*
 * 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.BlancoNameAdjuster;
import blanco.csv.resourcebundle.BlancoCsvReaderResourceBundle;
import blanco.csv.resourcebundle.BlancoCsvResourceBundle;
import blanco.csv.valueobject.BlancoCsvFieldStructure;
import blanco.csv.valueobject.BlancoCsvStructure;
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 BlancoCsvExpandReader {
    final BlancoCsvResourceBundle bundle = new BlancoCsvResourceBundle();

    final BlancoCsvReaderResourceBundle readerBundle = new BlancoCsvReaderResourceBundle();

    public void expand(final BlancoCsvStructure processStructure,
            final File directoryTarget) {

        final String className = BlancoNameAdjuster
                .toClassName(processStructure.getFileDefinitionId())
                + readerBundle.getClassNameSuffix();
        final Type typeCsvIOException = new Type(processStructure
                .getRuntimePackage()
                + readerBundle.getAddusingtype01Suffix());
        final ClassExpander classExpander = new ClassExpander(new Type(
                processStructure.getPackageName()
                        + readerBundle.getPackagePrefix(), className)) {
            protected void expandClassStruct() {
                addImport(typeCsvIOException);
                addFileComment(readerBundle.getFilecomment());

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

                final FieldExpander field1 = new FieldExpander(new Type(
                        readerBundle.getFieldReaderType()), readerBundle
                        .getFieldReaderName());
                field1.getJavaDoc().addLine(
                        readerBundle.getFieldReaderJavadoc01());
                field1.getJavaDoc().addLine(
                        readerBundle.getFieldReaderJavadoc02());
                addField(field1);

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

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

                    if (field.getType().equals("java.util.Date")) {
                        final FieldExpander field3 = new FieldExpander(
                                new Type(readerBundle
                                        .getFieldSimpleDateFormatType()),
                                readerBundle
                                        .getFieldSimpleDateFormatNamePrefix()
                                        + BlancoNameAdjuster.toClassName(field
                                                .getName()));
                        field3
                                .getJavaDoc()
                                .addLine(
                                        readerBundle
                                                .getFieldSimpleDateFormatJavadoc01(field
                                                        .getName()));
                        field3.getJavaDoc().addLine(
                                readerBundle
                                        .getFieldSimpleDateFormatJavadoc02());
                        addField(field3);
                    }
                }

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

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

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

                            if (field.getType().equals("java.util.Date")) {
                                getData()
                                        .addLine(
                                                readerBundle
                                                        .getFieldSimpleDateFormatNamePrefix()
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + " = new SimpleDateFormat("
                                                        + (field.getFormat() == null ? "\"yyyy/MM/dd\""
                                                                : "\""
                                                                        + field
                                                                                .getFormat()
                                                                        + "\"")
                                                        + ");");
                                getData().addLine("// 日付/時刻解析を厳密におこないます。");
                                getData()
                                        .addLine(
                                                readerBundle
                                                        .getFieldSimpleDateFormatNamePrefix()
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + ".setLenient(false);");
                            }
                        }
                    }
                });

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

                addMethod(new MethodExpander("readRecord") {
                    // メソッドのシグニチャ指定
                    public void setupSignature() {
                        getJavaDoc().addLine(
                                readerBundle.getReadrecordJavadoc());
                        getJavaDoc().addReturn(
                                readerBundle.getReadrecordReturnJavadoc());
                        getJavaDoc().addException(typeCsvIOException,
                                readerBundle.getReadrecordThrows01Javadoc());
                        getJavaDoc().addException(
                                new Type(readerBundle
                                        .getReadrecordThrows02Type()),
                                readerBundle.getReadrecordThrows02Javadoc());
                        addException(typeCsvIOException);
                        addException(new Type(readerBundle
                                .getReadrecordThrows02Type()));
                        setReturnType(new Type(recordClassName));
                    }

                    // メソッドの実装
                    public void implement() {
                        getData().addLine(
                                "final String line = fReader.readLine();");
                        getData().addLine("if (line == null) {");
                        getData().addLine(readerBundle.getReadrecordLine03());
                        getData().addLine("return null;");
                        getData().addLine("}");
                        getData().addLine("fLineCounter++;");
                        getData()
                                .addLine(
                                        readerBundle
                                                .getReadrecordLine07(BlancoNameAdjuster
                                                        .toClassName(processStructure
                                                                .getFileDefinitionId())));
                        addUsingType(new Type("java.io.StringReader"));
                        getData()
                                .addLine(
                                        "final StringReader reader = new StringReader(line);");
                        getData().addLine("String tokenString = null;");

                        for (int indexField = 0; indexField < processStructure
                                .getListField().size(); indexField++) {
                            final BlancoCsvFieldStructure field = (BlancoCsvFieldStructure) processStructure
                                    .getListField().get(indexField);

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

                            addUsingType(new Type(processStructure
                                    .getRuntimePackage()
                                    + ".util.BlancoCsvRuntimeUtil"));
                            if (field.getType().endsWith("(quote)")) {
                                // 文字列のクオート付。
                                getData().addLine(
                                        readerBundle.getReadrecordLine21());
                                getData()
                                        .addLine(
                                                readerBundle
                                                        .getReadrecordLine22Case01(
                                                                processStructure
                                                                        .getDelimiter(),
                                                                (indexField == processStructure
                                                                        .getListField()
                                                                        .size() - 1 ? "true"
                                                                        : "false")));
                            } else {
                                getData()
                                        .addLine(
                                                readerBundle
                                                        .getReadrecordLine22Case02(
                                                                processStructure
                                                                        .getDelimiter(),
                                                                (indexField == processStructure
                                                                        .getListField()
                                                                        .size() - 1 ? "true"
                                                                        : "false")));
                            }
                            getData().addLine("if (tokenString == null) {");
                            getData()
                                    .addLine(
                                            "throw new BlancoCsvIOException(\""
                                                    + bundle
                                                            .getCsvReaderErr001(getLocationString(
                                                                    indexField,
                                                                    field
                                                                            .getNo(),
                                                                    field
                                                                            .getName(),
                                                                    field
                                                                            .getDescription()))
                                                    + "\");");
                            getData().addLine("}");

                            final String encodingString = (processStructure
                                    .getEncoding() == null ? "" : "\""
                                    + processStructure.getEncoding() + "\"");
                            if (field.getRequired()) {
                                getData().addLine("// 必須項目。");
                                getData().addLine(
                                        "if (tokenString.length() == 0) {");
                                getData()
                                        .addLine(
                                                "throw new BlancoCsvIOException(\""
                                                        + bundle
                                                                .getCsvReaderErr008(getLocationString(
                                                                        indexField,
                                                                        field
                                                                                .getNo(),
                                                                        field
                                                                                .getName(),
                                                                        field
                                                                                .getDescription()))
                                                        + "\");");
                                getData().addLine("}");
                            } else {
                                getData().addLine("// 任意項目。");
                                getData().addLine(
                                        "if (tokenString.length() == 0) {");
                                if (field.getType().startsWith(
                                        "java.lang.String")) {
                                    getData()
                                            .addLine(
                                                    "// 必須項目ではない文字列項目に長さ0の値が読み込まれた場合には、読み込み後の値としても長さ0の文字列とします。");
                                    getData().addLine(
                                            "record.set"
                                                    + BlancoNameAdjuster
                                                            .toClassName(field
                                                                    .getName())
                                                    + "(tokenString);");
                                } else {
                                    getData()
                                            .addLine(
                                                    "// 必須項目ではない項目に長さ0の値が読み込まれた場合には、値としてnullを代入します。");
                                    getData().addLine(
                                            "record.set"
                                                    + BlancoNameAdjuster
                                                            .toClassName(field
                                                                    .getName())
                                                    + "(null);");
                                }
                                getData().addLine("} else {");
                            }
                            if (field.getMinLength() != null) {
                                getData().addLine(
                                        "if (tokenString.getBytes("
                                                + encodingString
                                                + ").length < "
                                                + field.getMinLength() + ") {");
                                getData()
                                        .addLine(
                                                "throw new BlancoCsvIOException(\""
                                                        + bundle
                                                                .getCsvReaderErr002(
                                                                        getLocationString(
                                                                                indexField,
                                                                                field
                                                                                        .getNo(),
                                                                                field
                                                                                        .getName(),
                                                                                field
                                                                                        .getDescription()),
                                                                        field
                                                                                .getMinLength())
                                                        + "\");");
                                getData().addLine("}");
                            }
                            if (field.getMaxLength() != null) {
                                getData().addLine(
                                        "if (tokenString.getBytes("
                                                + encodingString
                                                + ").length > "
                                                + field.getMaxLength() + ") {");
                                getData()
                                        .addLine(
                                                "throw new BlancoCsvIOException(\""
                                                        + bundle
                                                                .getCsvReaderErr003(
                                                                        getLocationString(
                                                                                indexField,
                                                                                field
                                                                                        .getNo(),
                                                                                field
                                                                                        .getName(),
                                                                                field
                                                                                        .getDescription()),
                                                                        field
                                                                                .getMaxLength())
                                                        + "\");");
                                getData().addLine("}");
                            }

                            if (field.getType().equals("java.lang.String")
                                    || field.getType().equals(
                                            "java.lang.String(quote)")) {
                                getData().addLine(
                                        "record.set"
                                                + BlancoNameAdjuster
                                                        .toClassName(field
                                                                .getName())
                                                + "(tokenString);");
                            } else if (field.getType().equals("int")) {
                                getData().addLine("try {");
                                if (field.getRequired()) {
                                    // 必須の場合
                                    getData()
                                            .addLine(
                                                    "record.set"
                                                            + BlancoNameAdjuster
                                                                    .toClassName(field
                                                                            .getName())
                                                            + "(Integer.parseInt(tokenString));");
                                } else {
                                    getData()
                                            .addLine(
                                                    "record.set"
                                                            + BlancoNameAdjuster
                                                                    .toClassName(field
                                                                            .getName())
                                                            + "(new Integer(tokenString));");
                                }
                                getData().addLine(
                                        "} catch (NumberFormatException ex) {");
                                getData()
                                        .addLine(
                                                "throw new BlancoCsvIOException(\""
                                                        + bundle
                                                                .getCsvReaderErr004(getLocationString(
                                                                        indexField,
                                                                        field
                                                                                .getNo(),
                                                                        field
                                                                                .getName(),
                                                                        field
                                                                                .getDescription()))
                                                        + "\" + ex.toString(), ex);");
                                getData().addLine("}");
                            } else if (field.getType().equals("long")) {
                                getData().addLine("try {");
                                if (field.getRequired()) {
                                    // 必須の場合
                                    getData()
                                            .addLine(
                                                    "record.set"
                                                            + BlancoNameAdjuster
                                                                    .toClassName(field
                                                                            .getName())
                                                            + "(Long.parseLong(tokenString));");
                                } else {
                                    getData()
                                            .addLine(
                                                    "record.set"
                                                            + BlancoNameAdjuster
                                                                    .toClassName(field
                                                                            .getName())
                                                            + "(new Long(tokenString));");
                                }
                                getData().addLine(
                                        "} catch (NumberFormatException ex) {");
                                getData()
                                        .addLine(
                                                "throw new BlancoCsvIOException(\""
                                                        + bundle
                                                                .getCsvReaderErr005(getLocationString(
                                                                        indexField,
                                                                        field
                                                                                .getNo(),
                                                                        field
                                                                                .getName(),
                                                                        field
                                                                                .getDescription()))
                                                        + "\" + ex.toString(), ex);");
                                getData().addLine("}");
                            } else if (field.getType().equals("java.util.Date")) {
                                addUsingType(new Type(
                                        "java.text.ParseException"));
                                getData().addLine("try {");
                                getData().addLine(
                                        "record.set"
                                                + BlancoNameAdjuster
                                                        .toClassName(field
                                                                .getName())
                                                + "(fSimpleDateFormat"
                                                + BlancoNameAdjuster
                                                        .toClassName(field
                                                                .getName())
                                                + ".parse(tokenString));");
                                getData().addLine(
                                        "} catch (ParseException ex) {");
                                getData()
                                        .addLine(
                                                "throw new BlancoCsvIOException(\""
                                                        + bundle
                                                                .getCsvReaderErr006(
                                                                        getLocationString(
                                                                                indexField,
                                                                                field
                                                                                        .getNo(),
                                                                                field
                                                                                        .getName(),
                                                                                field
                                                                                        .getDescription()),
                                                                        BlancoNameAdjuster
                                                                                .toClassName(field
                                                                                        .getName()))
                                                        + "\" + ex.toString(), ex);");
                                getData().addLine("}");
                            } else if (field.getType().equals(
                                    "java.math.BigDecimal")) {
                                addImport(new Type("java.math.BigDecimal"));
                                getData().addLine("try {");
                                getData()
                                        .addLine(
                                                "record.set"
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + "(new BigDecimal(tokenString));");
                                getData().addLine(
                                        "} catch (NumberFormatException ex) {");
                                getData()
                                        .addLine(
                                                "throw new BlancoCsvIOException(\""
                                                        + bundle
                                                                .getCsvReaderErr007(getLocationString(
                                                                        indexField,
                                                                        field
                                                                                .getNo(),
                                                                        field
                                                                                .getName(),
                                                                        field
                                                                                .getDescription()))
                                                        + "\" + ex.toString(), ex);");
                                getData().addLine("}");
                            } else {
                                getData().addLine(
                                        bundle.getNotSupportedType(field
                                                .getType()));
                            }

                            if (field.getRequired()) {
                                // 必須項目。
                            } else {
                                getData().addLine("}");
                            }
                        }

                        getData().addLine("return record;");
                    }

                });

                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("close") {
                    // メソッドのシグニチャ指定
                    public void setupSignature() {
                        getJavaDoc().addLine(readerBundle.getCloseJavadoc01());
                        getJavaDoc().addLine(readerBundle.getCloseJavadoc02());
                        getJavaDoc().addException(
                                new Type(readerBundle.getCloseThrows01Type()),
                                readerBundle.getCloseThrows01Javadoc());
                        addException(new Type(readerBundle
                                .getCloseThrows01Type()));
                    }

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

        ClassExpander.generateJavaSource(classExpander, directoryTarget);
    }

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