/*
 * blancoDb
 * Copyright (C) 2004-2005 Yasuo Nakanishi
 * 
 * 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.db.definition;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import blanco.ig.expander.NameAdjuster;

/**
 * @author Yasuo Nakanishi
 */
public class TableGateway {
    private String _dbName = "";

    private String _className = "";

    private String _alias = "";

    private List _fieldList = new ArrayList();

    private List _keyFieldList = null;

    public TableGateway(String name) {
        _dbName = name;
        _className = createClassName(name);
    }

    private String createClassName(String name) {
        NameAdjuster adjuster = new NameAdjuster();
        return adjuster.toClassName(name.replaceAll(" ", "")
                .replaceAll("_", ""));
    }

    public boolean hasDataField() {
        boolean result = false;
        TableField field = null;
        for (int i = 0; i < getFiledCount(); i++) {
            field = getField(i);
            if (!field.isPrimaryKey()) {
                result = true;
                break;
            }
        }
        return result;
    }

    public boolean exsistPrimaryKey() {
        boolean result = false;
        for (int i = 0; i < getFiledCount(); i++) {
            if (getField(i).isPrimaryKey()) {
                result = true;
                break;
            }
        }
        return result;
    }

    public void addField(TableField fieldDefine) {
        _fieldList.add(fieldDefine);
    }

    public int getFiledCount() {
        return _fieldList.size();
    }

    public TableField getField(int index) {
        return (TableField) _fieldList.get(index);
    }

    public Iterator getFieldIterator() {
        return _fieldList.iterator();
    }

    public String getDbName() {
        return _dbName;
    }

    public String getClassName() {
        String result = _className;
        if (!_alias.equals("")) {
            result = _alias;
        }
        return result;
    }

    public Iterator getPrimaryKeyFieldIterator() {
        TableField field = null;

        if (_keyFieldList == null) {
            _keyFieldList = new ArrayList();
            Iterator i = getFieldIterator();
            while (i.hasNext()) {
                field = (TableField) i.next();
                if (field.isPrimaryKey()) {
                    _keyFieldList.add(field);
                }
            }
        }
        return _keyFieldList.iterator();
    }

    public void setAlias(String alias) {
        _alias = alias;
    }
}