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

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

    private String _className = "";

    private final List _fieldList = new ArrayList();

    private List _keyFieldList = null;

    public TableGateway(final String name) {
        _dbName = name;
        _className = BlancoNameAdjuster.toClassName(name);
    }

    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(final TableField fieldDefine) {
        _fieldList.add(fieldDefine);
    }

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

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

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

    public String getDbName() {
        return _dbName;
    }

    public String getClassName() {
        String result = _className;
        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();
    }
}