package org.jfox.dao.mapping;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.jfox.dao.DAOException;
import org.jfox.dao.DAOUtil;

/**
 * @author <a href="mailto:yangyong@ufsoft.com.cn">Young Yang</a>
 */

public class TableMapping {
    protected String tableName = null;
    protected String primaryKeyColumnName = null;

    protected Class mappingClass;

    /**
     * columns mapping
     */
    protected Map columnMappings = new HashMap();

    public TableMapping(String tableName, Class mappingClass) {
        this.tableName = tableName;
        this.mappingClass = mappingClass;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getPrimaryKeyColumnName() {
        return primaryKeyColumnName;
    }

    public void setPrimaryKeyColumnName(String primaryKeyColumnName) {
        this.primaryKeyColumnName = primaryKeyColumnName;
    }

    public void setColumnAutoEvaluated(String columnName) throws DAOException {
        if(!isColumnMapped(columnName)){
            throw new DAOException("column " + columnName + " not exists in table " + getTableName());
        }
        getColumnMapping(columnName).setAutoEvaluated(true);
    }

    /**
     * find all multi names with provided column name
     * @param columnName
     * @throws DAOException
     */
    public void setColumnAutoEvaluatedWithMutilName(String columnName) throws DAOException {
        String[] names = DAOUtil.multiNames(columnName);
        boolean set = false;
        for(int i=0; i<names.length; i++){
            String name = names[i];
            if(isColumnMapped(name)){
                getColumnMapping(name).setAutoEvaluated(true);
                set = true;
            }
        }
        if(!set){
            throw new DAOException("column " + columnName + " not exists in table " + getTableName() + ", multi name are " + Arrays.asList(names));
        }
    }

    public Class getMappingClass() {
        return mappingClass;
    }

    public void setMappingClass(Class mappingClass) {
        this.mappingClass = mappingClass;
    }

    public void addColumnMapping(ColumnMapping columnMapping) {
        columnMappings.put(columnMapping.getColumnName(),columnMapping);
    }

    public ColumnMapping getColumnMapping(String column){
        return (ColumnMapping)columnMappings.get(column);
    }

    public int getMappingColumnSize(){
        return columnMappings.size();
    }

    public Collection getColumnMappings(){
        return Collections.unmodifiableCollection(columnMappings.values());
    }

    public boolean isColumnMapped(String columnName){
        return columnMappings.containsKey(columnName);
    }

    public static void main(String[] args) {

    }
}

