/*
 * 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.Writer;
import java.util.Iterator;
import java.util.Map;

import org.seasar.codegen.Java;
import org.seasar.codegen.element.Table;

import freemarker.template.Configuration;

@Java
public class AbstractRelationEntityOutputCodeImpl extends
        AbstractEntityOutputCodeImpl {

    public AbstractRelationEntityOutputCodeImpl() {
        super.setDefaultDir("Dto");
        super.setTemplateFileName("abstractPackDto.ftl");
        super
                .setFileNameFtl("Abstract${table.tableNameForDto?cap_first}Relation.java");
    }

    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();
            if (isProcessTable(tableList, key)) {
                Map<String, Object> root = createRootObj(tableList, key);
                convetName(root);
                Writer out = createWriter(baseDir, root);
                if (out == null) {
                    continue;
                }
                processTemplate(cfg, root, out);
                destroyWriter(out);
            }
        }
    }

    protected boolean isProcessTable(Map<String, Table> tableList, String key) {
        Table table = tableList.get(key);
        return (table.getParentTableName().size() > 0);
    }

    protected Map<String, Object> createRootObj(Map<String, Table> tableList,
            String key) {
        Map<String, Object> root = super.createRootObj(tableList, key);
        root.put("tableMap", tableList);
        return root;
    }

}
