/*
 * Branch.java
 */
import java.sql.*;

/** Objects of the Branch class represent records in the 
 * branches table in the database.
 * @author Timothy Paul Fox
 * @version August 02, 2004, 7:58 PM
 */
public class Branch {
    
    private BranchID branchID;
    private String policyID;
    private java.sql.Date dateAdded;
    private java.sql.Date dateRetired;
    private long contactID;
    
    private Statement userStmt;
    private Connection dbWire;
    private ResultSet rowRS;
    private boolean isNewRow;
    
    {
        branchID = null;
        policyID = null;
        dateAdded = null;
        dateRetired = null;
        contactID = 0;
        
        userStmt = null;
        dbWire = null;
        rowRS = null;
        isNewRow = false;
    }
    
    /** Creates a new Branch object and record
     * @param contactId is the long integer value that is the primary
     * key of a record in the contactinfo table.
     * This record (created by instantiating a ContactInfo object)
     * must exist before the new Branch object is created.
     * @throws Exception any problem that happens in creating the 
     * Branch object. (LAZY)
     */
    public Branch(long contactId)  throws Exception {
        isNewRow = true;
        branchID = new BranchID();
        if (contactId < 1) 
            throw new IllegalArgumentException(
                                "User():illegal contactId value");
        try {
            ContactInfo idCheck = new ContactInfo(contactID);
        }
        catch (Exception e) {
            throw new IllegalArgumentException(
                "Branch():could not confirm ContactInfo for contactID");
        }
        
        try {
            makeDbConnection("root");
        
            contactID = contactId;
            dateAdded = new java.sql.Date(System.currentTimeMillis());
            int result;
            String valueString; 
            valueString = "'" + getBranchID() + "'," + "'P00'" +
                          "'" + dateAdded.toString() + "'," +
                          contactID ;

            result = putToRow(
                    "INSERT INTO branches " +
                    "(branch_id, policy_id, date_added, contact_id) " +
                    "VALUES (" + valueString + ")");
            if (result != 1) 
                throw new SQLException("New branch record not written");
        }
        finally {
            if (userStmt != null) userStmt.close();
            if (dbWire != null) dbWire.close();
        }
    } // end Branch (contactID)

    /** Creates an object that is a copy of an existing 
     * branches record.
     * Tries to find a record in the branches
     * table whose primary key matches knownID. If it finds the
     * record, it instantiates a Branch object and reads the
     * record's data into the object's properties.
     * @param knownID This String must start with ' B ', not case
     * sensitive. The rest of the string must parse as a long
     * integer. If the ID does not match that of a record in the
     * branches table, the constructor will throw 
     * SQLException.
     * @throws Exception any problem that happens in creating the 
     * Branch object. (LAZY)
     */    
    public Branch(String knownID) throws Exception {
        branchID = new BranchID(knownID);
        try {
            makeDbConnection("root");
            getFromRow("SELECT * from branches " +
                       "WHERE (branch_id = '" + getBranchID() +  "')");
            rowRS.first();
            policyID = rowRS.getString("policy_id");
            dateAdded = rowRS.getDate("date_added");
            dateRetired = rowRS.getDate("date_retired");
            contactID = rowRS.getInt("contact_id");
        }
        finally {
            if (userStmt != null) userStmt.close();
            if (dbWire != null) dbWire.close();
        }
    } // end Branch(knownID)
    
    private void getFromRow(String query) throws Exception {
        rowRS = userStmt.executeQuery(query);
    }
    
    private void makeDbConnection(String user) throws Exception {
        LibManDbConnection plug;
        
        if (dbWire != null) {
            dbWire.close();
        }
        plug = new LibManDbConnection(user);
        dbWire = plug.connect();
        userStmt = dbWire.createStatement();
    }
    
    private int putToRow(String updateSpec) throws Exception{
        return userStmt.executeUpdate(updateSpec);
    }
    
    /** describes the properties of the User object.
     * @return description of the User object
     */    
    public String toString() {
        StringBuffer sb = new StringBuffer("Branch: ");
        sb.append(getBranchID() + ":");
        sb.append("added>");
        sb.append((null == getDateAdded())? 
                            "Unknown" : getDateAdded().toString());
        sb.append((null == getDateRetired())? 
                            ":?" : ":retired>" +
                            getDateAdded().toString());
        sb.append(":" + getContactID());
        return sb.toString();
    } // end toString()
    
    /** gets branchID from the Branch object. 
     * @return A ten character string that starts with an uppercase 
     * ' B ', followed by a nine character string of the object's
     * numeric value, left-padded with zeros.
     */    
    public String getBranchID() {
        return branchID.toString();
    }
    

    public String contactInfoString() {
        String s;
        try {
            ContactInfo info = new ContactInfo(getContactID());
            return info.toString();
        }
        catch (Exception e) {
        }
        return "";
    }
 
    /** gets the date the Branch record was added to the
     * users table.
     * @return a reference to a Date object
     */    
    public java.sql.Date getDateAdded() {
        return dateAdded;
    }
    
    /** gets the date the Branch record was retired. 
     * If the record has not been retired, returns null.
     * @return a reference to a Date object, or null
     */    
    public java.sql.Date getDateRetired() {
        return dateRetired;
    }
   
    /** gets the contactID
     * @return the long integer that is primary key of the contact
     * infomation record for this branch
     */
    public long getContactID() {
        return contactID;
    }
    
    /** indicates whether the branch record has been retired
     * @return true if the dateRetired property has 
     * been set, otherwise false
     */    
    public boolean isRetired() /* throws Exception */ {
        if (
            (!isNewRow) && (dateRetired != null) &&
            (dateAdded != null) && 
            (dateAdded.compareTo(dateRetired) < 0)
            )
            return true;
        else
            return false;
    } // end isRetired
    
    /** marks a branch record as retired. The Branch object must be
     * one that was created by reading the
     * branches table.
     * @throws Exception any exception from accessing the database,
     * plus IllegalArgumentException if retire() is called on a
     * record that is already retired.
     */    
    public void retire() throws Exception {
        String valueString; 
        int result;
        if (isNewRow) 
            throw new IllegalArgumentException(
                "Branch:Cannot retire() a newly created record!");
        if (isRetired())
            throw new IllegalArgumentException(
                "Branch:Cannot retire() a retired record!");
            
        dateRetired = new java.sql.Date(System.currentTimeMillis());
        valueString = "'" + dateRetired.toString() + "'";
        try {
            makeDbConnection("root");
            result = putToRow("UPDATE branches " +
                              "SET date_retired = " + valueString + 
                              "WHERE (branch_id = '" + getBranchID()
                              + "')");
        }
        finally {
            if (userStmt != null) userStmt.close();
            if (dbWire != null) dbWire.close();
        }
    } // end retire()
    
} // end class User