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

import java.util.Iterator;
import java.util.Map;

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

/**
 * @author azusa
 * 
 */
public class LinkUtil {

    private LinkUtil() {
    }

    public static void setupChildLinks(Map<String, Table> tableMap) {
        for (Iterator<Table> i = tableMap.values().iterator(); i.hasNext();) {
            setupChildLinks(i.next(), tableMap);
        }
    }

    private static void setupChildLinks(Table child, Map<String, Table> tableMap) {
        for (Iterator<LinkTable> i = child.getParentTable().iterator(); i
                .hasNext();) {
            LinkTable parentLink = (LinkTable) i.next();
            String tableName = parentLink.getTableName();
            Table parent = (Table) tableMap.get(tableName);
            LinkTable childLink = getChildLink(child, parentLink);
            parent.addChildTable(tableName, childLink);
        }
    }

    private static LinkTable getChildLink(Table child, LinkTable parentLink) {
        LinkTable link = new LinkTable();
        link.setTableName(child.getTableName());
        link.setParentFieldName(parentLink.getParentFieldName());
        link.setChildFieldName(parentLink.getChildFieldName());
        return link;
    }

}
