/*
 * Copyright 2009 Lari Natri <lari.natri@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


package compid.data.tuples;

import java.util.HashMap;

/**
 * Represents one tuple in a database table
 * @author Lari Natri
 */
public abstract class Tuple {
    
    public static final String PKLABELPOSTFIX = "_ID";
    
    public static final int PK_NOTSET = -1;
    public static final int PK_ERRORINSERTING = -2;
    
    protected int primaryKey = PK_NOTSET;
    protected HashMap<String,Object> foreignKeys = null;

    /** Get primary key, -1 if not set */
    public int getPrimaryKey() {
        return primaryKey;
    }    

    /** Set primary key (from database) */
    public void setPrimaryKey(int primaryKey) {
        this.primaryKey = primaryKey;
    }

    /** Sets foreign keys from database */
    public void setAllForeignKeys(HashMap<String,Object> foreignKeys) {
        this.foreignKeys = foreignKeys;
    }
    
    /** Gets the foreign keys set before with setAllForeignKeys. If
     *  they are not set, null will be returned.
     * @return
     */
    public HashMap<String,Object> getForeignKeys() {
        return this.foreignKeys;
    }
    
    /** Get primary key's label */
    public String getPrimaryKeyLabel() {
        return this.getTableLabel()+PKLABELPOSTFIX;
    };
    
    /**
     * This method is ment to be called from the constructor of derived
     * classes if they have no references to other tuples.
     */
    protected void setTupleHasNoForeignKeys() {
        this.setAllForeignKeys(new HashMap<String,Object>(0,1));
    }
    
    // --- Abstract methods ---
    
    /** Get table's label */
    public abstract String getTableLabel();

    /** Get all column labels and their values (not including foreign keys) */
    public abstract HashMap<String,Object> getColsAndValues();
    
    /** Get all keys and values to be used in primary key searches.
        Default implementation calls for getColsAndValues(). Should
        be overwritten in such derived classes, that determine the
        existence of a tuple in a database by only a subset of columns.
     */
    public HashMap<String,Object> getKeysAndValuesForExistenceCheck() {
        HashMap<String,Object> map = this.getColsAndValues();
        map.putAll(this.getForeignKeys());
        return map;
    }
   

}
