/*
 * 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 java.math.BigDecimal;

import blanco.commons.util.BlancoNameAdjuster;
import blanco.fixedlength.resourcebundle.BlancoFixedLengthReaderResourceBundle;
import blanco.fixedlength.resourcebundle.BlancoFixedLengthResourceBundle;
import blanco.fixedlength.valueobject.BlancoFixedLengthFieldStructure;
import blanco.fixedlength.valueobject.BlancoFixedLengthStructure;
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 BlancoFixedLengthExpandReader {
    final BlancoFixedLengthResourceBundle bundle = new BlancoFixedLengthResourceBundle();

    final BlancoFixedLengthReaderResourceBundle readerBundle = new BlancoFixedLengthReaderResourceBundle();

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

        final String className = BlancoNameAdjuster
                .toClassName(processStructure.getFileDefinitionId())
                + readerBundle.getClassNameSuffix();
        final Type typeIOException = new Type(processStructure
                .getRuntimePackage()
                + readerBundle.getAddusingtype01Suffix());
        final ClassExpander classExpander = new ClassExpander(new Type(
                processStructure.getPackageName()
                        + readerBundle.getPackagePrefix(), className)) {
            protected void expandClassStruct() {
                addImport(typeIOException);
                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 BlancoFixedLengthFieldStructure field = (BlancoFixedLengthFieldStructure) 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 BlancoFixedLengthFieldStructure field = (BlancoFixedLengthFieldStructure) 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()) + "FixedLengthRecord";

                addMethod(new MethodExpander("readRecord") {
                    // メソッドのシグニチャ指定
                    public void setupSignature() {
                        getJavaDoc().addLine(
                                readerBundle.getReadrecordJavadoc());
                        getJavaDoc().addReturn(
                                readerBundle.getReadrecordReturnJavadoc());
                        getJavaDoc().addException(typeIOException,
                                readerBundle.getReadrecordThrows01Javadoc());
                        getJavaDoc().addException(
                                new Type(readerBundle
                                        .getReadrecordThrows02Type()),
                                readerBundle.getReadrecordThrows02Javadoc());
                        addException(typeIOException);
                        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 BlancoFixedLengthFieldStructure field = (BlancoFixedLengthFieldStructure) 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.BlancoFixedLengthRuntimeUtil"));
                            final String encodingStringOrNull = processStructure
                                    .getEncoding() == null ? "null" : "\""
                                    + processStructure.getEncoding() + "\"";
                            getData().addLine(
                                    readerBundle.getReadrecordLine22(
                                            new BigDecimal(String.valueOf(field
                                                    .getLength())),
                                            encodingStringOrNull));

                            final String encodingStringOrBlank = (processStructure
                                    .getEncoding() == null ? "" : "\""
                                    + processStructure.getEncoding() + "\"");
                            getData().addLine(
                                    "if (tokenString.getBytes("
                                            + encodingStringOrBlank
                                            + ").length < " + field.getLength()
                                            + ") {");
                            getData()
                                    .addLine(
                                            "throw new BlancoFixedLengthIOException(\""
                                                    + bundle
                                                            .getCsvReaderErr002(
                                                                    getLocationString(
                                                                            indexField,
                                                                            field
                                                                                    .getNo(),
                                                                            field
                                                                                    .getName(),
                                                                            field
                                                                                    .getDescription()),
                                                                    field
                                                                            .getLength())
                                                    + "\");");
                            getData().addLine("}");

                            getData().addLine(
                                    "if (tokenString.getBytes("
                                            + encodingStringOrBlank
                                            + ").length > " + field.getLength()
                                            + ") {");
                            getData()
                                    .addLine(
                                            "throw new BlancoFixedLengthIOException(\""
                                                    + bundle
                                                            .getCsvReaderErr003(
                                                                    getLocationString(
                                                                            indexField,
                                                                            field
                                                                                    .getNo(),
                                                                            field
                                                                                    .getName(),
                                                                            field
                                                                                    .getDescription()),
                                                                    field
                                                                            .getLength())
                                                    + "\");");
                            getData().addLine("}");

                            if (field.getType().equals("java.lang.String")) {
                                getData().addLine(
                                        "record.set"
                                                + BlancoNameAdjuster
                                                        .toClassName(field
                                                                .getName())
                                                + "(tokenString);");
                            } else if (field.getType().equals("int")) {
                                getData().addLine("try {");
                                getData()
                                        .addLine(
                                                "record.set"
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + "(Integer.parseInt(tokenString.trim()));");
                                getData().addLine(
                                        "} catch (NumberFormatException ex) {");
                                getData()
                                        .addLine(
                                                "throw new BlancoFixedLengthIOException(\""
                                                        + bundle
                                                                .getCsvReaderErr004(getLocationString(
                                                                        indexField,
                                                                        field
                                                                                .getNo(),
                                                                        field
                                                                                .getName(),
                                                                        field
                                                                                .getDescription()))
                                                        + "\" + ex.toString(), ex);");
                                getData().addLine("}");
                            } else if (field.getType().equals("long")) {
                                getData().addLine("try {");
                                getData()
                                        .addLine(
                                                "record.set"
                                                        + BlancoNameAdjuster
                                                                .toClassName(field
                                                                        .getName())
                                                        + "(Long.parseLong(tokenString.trim()));");
                                getData().addLine(
                                        "} catch (NumberFormatException ex) {");
                                getData()
                                        .addLine(
                                                "throw new BlancoFixedLengthIOException(\""
                                                        + 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 BlancoFixedLengthIOException(\""
                                                        + 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.trim()));");
                                getData().addLine(
                                        "} catch (NumberFormatException ex) {");
                                getData()
                                        .addLine(
                                                "throw new BlancoFixedLengthIOException(\""
                                                        + bundle
                                                                .getCsvReaderErr007(getLocationString(
                                                                        indexField,
                                                                        field
                                                                                .getNo(),
                                                                        field
                                                                                .getName(),
                                                                        field
                                                                                .getDescription()))
                                                        + "\" + ex.toString(), ex);");
                                getData().addLine("}");
                            } else {
                                getData().addLine(
                                        bundle.getNotSupportedType(field
                                                .getType()));
                            }

                        }

                        // 全ての項目を読み切った後にデータが残っていないことを確認。
                        getData().addLine("");
                        getData().addLine("if (reader.read() >= 0) {");
                        getData().addLine(
                                "throw new BlancoFixedLengthIOException(\""
                                        + bundle.getCsvReaderErr009() + "\");");
                        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));
    }
}
