/*
 * Copyright 2006-2011 the Seasar Foundation and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package org.seasar.codegen.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.seasar.buri.common.util.template.TextTemplate;
import org.seasar.buri.common.util.template.exception.TemplateRuntimeException;
import org.seasar.codegen.CodeGenConfig;
import org.seasar.codegen.OutputCode;
import org.seasar.codegen.convert.NameConverter;
import org.seasar.codegen.element.Table;
import org.seasar.codegen.util.FileUtil;
import org.seasar.framework.exception.IORuntimeException;
import org.seasar.framework.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class NormalEntityOutputCodeImpl implements OutputCode {
    protected String defaultDir = "Dto";

    protected String dirNameFtl = "${package?replace(\".\",\"/\")}/${defaultDir?lower_case?replace(\".\",\"/\")}/";

    protected String fileNameFtl = "Abstract${table.tableNameForDto?cap_first}.java";

    protected String templateDir = "fm/java/";

    protected String templateFileName = "normalEntity.ftl";

    protected String packageName;

    private Map<String, Object> addRootObj = new HashMap<String, Object>();

    protected TextTemplate template;

    private NameConverter converter;

    public static final String encoding_BINDING = "bindingType=may";

    protected String encoding = "UTF-8";

    public static final String codegenConfig_BINDING = "bindingType=may";

    private CodeGenConfig codegenConfig = new CodeGenConfigImpl();

    public void generateCode(File baseDir, Map<String, Table> tableList) {
        Configuration cfg = getConfiguration();
        Iterator<String> ite = tableList.keySet().iterator();
        while (ite.hasNext()) {
            String key = ite.next();
            Map<String, Object> root = createRootObj(tableList, key);
            convetName(root);
            Writer out = null;
            try {
                // TODO リファクタリング
                out = createWriter(baseDir, root);
                // generation gapの場合
                if (out == null) {
                    continue;
                }
                processTemplate(cfg, root, out);
            } finally {
                destroyWriter(out);
            }
        }
    }

    protected void destroyWriter(Writer out) {
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (Exception e) {
        }
    }

    protected void processTemplate(Configuration cfg, Map<String, Object> root,
            Writer out) {
        Template temp = createTemplate(cfg);
        try {
            temp.process(root, out);
        } catch (TemplateException e) {
            throw new TemplateRuntimeException(e);
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }

    }

    protected Writer createWriter(File baseDir, Map<String, Object> root) {
        String outputDirName = baseDir.getPath() + File.separator
                + template.process(dirNameFtl, root);
        ;
        String outputFileName = template.process(fileNameFtl, root);
        Writer writer = null;
        try {
            File file = new File(outputDirName);
            file.mkdirs();
            writer = new OutputStreamWriter(new FileOutputStream(outputDirName
                    + outputFileName), encoding);
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
        return writer;
    }

    protected Template createTemplate(Configuration cfg) {
        Template temp = null;
        try {
            temp = cfg.getTemplate(templateFileName);
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
        return temp;
    }

    protected Map<String, Object> createRootObj(Map<String, Table> tableList,
            String key) {
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("table", tableList.get(key));
        root.put("package", packageName);
        root.put("defaultDir", defaultDir);
        root.putAll(addRootObj);
        if (!StringUtil.isEmpty(codegenConfig.getHeaderTemplatePath())) {
            root.put("header", FileUtil.readText(codegenConfig
                    .getHeaderTemplatePath(), encoding));
        } else {
            root.put("header", "");
        }
        if (codegenConfig.isTimestamp()) {
            root.put("timestampPropertyName", codegenConfig
                    .getTimestampPropertyName());
        }
        if (codegenConfig.isVersionNo()) {
            root.put("versionNoPropetyName", codegenConfig
                    .getVersionNoPropertyName());
        }
        return root;
    }

    protected void convetName(Map<String, Object> root) {
        converter.convert(root);
    }

    protected Configuration getConfiguration() {
        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(new File(templateDir));
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        cfg.setDefaultEncoding("UTF-8");
        return cfg;
    }

    public void addRootObjct(String name, Object data) {
        addRootObj.put(name, data);
    }

    public String getDefaultDir() {
        return defaultDir;
    }

    public void setDefaultDir(String defaultDir) {
        this.defaultDir = defaultDir;
    }

    public String getFileNameFtl() {
        return fileNameFtl;
    }

    public void setFileNameFtl(String fileNameFtl) {
        this.fileNameFtl = fileNameFtl;
    }

    public TextTemplate getTemplate() {
        return template;
    }

    public void setTemplate(TextTemplate template) {
        this.template = template;
    }

    public String getTemplateDir() {
        return templateDir;
    }

    public void setTemplateDir(String templateDir) {
        this.templateDir = templateDir;
    }

    public String getTemplateFileName() {
        return templateFileName;
    }

    public void setTemplateFileName(String templateFileName) {
        this.templateFileName = templateFileName;
    }

    public String getPackageName() {
        return packageName;
    }

    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }

    public void setDirNameFtl(String dirNameFtl) {
        this.dirNameFtl = dirNameFtl;
    }

    public void setNameConverter(NameConverter converter) {
        this.converter = converter;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public void setCodegenConfig(CodeGenConfig codegenConfig) {
        this.codegenConfig = codegenConfig;
    }

}
