/**
 * Copyright (c) 2006, yher2.net
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation 
 *   and/or other materials provided with the distribution.
 * * Neither the name of the nor the names of its contributors may be used to endorse or 
 *   promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE.
 */
package net.yher2.workstyle.torque;


import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import net.yher2.workstyle.torque.bean.StatusBean;
import net.yher2.workstyle.torque.bean.TaskBean;

import org.apache.commons.collections.map.IdentityMap;
import org.apache.commons.lang.ObjectUtils;
import org.apache.torque.TorqueException;
import org.apache.torque.om.BaseObject;
import org.apache.torque.om.NumberKey;
import org.apache.torque.om.ObjectKey;
import org.apache.torque.om.SimpleKey;
import org.apache.torque.util.Criteria;
import org.apache.torque.util.Transaction;
            

/**
 * This class was autogenerated by Torque on:
 *
 * [Thu Jan 26 23:30:02 JST 2006]
 *
 * You should not use this class directly.  It should not even be
 * extended all references should be to Status
 */
public abstract class BaseStatus extends BaseObject
{
    /** The Peer class */
    private static final StatusPeer peer =
        new StatusPeer();

        
    /** The value for the statusId field */
    private int statusId;
      
    /** The value for the name field */
    private String name;
                                          
    /** The value for the sortOrder field */
    private int sortOrder = 0;
      
    /** The value for the image field */
    private String image;
  
            
    /**
     * Get the StatusId
     *
     * @return int
     */
    public int getStatusId()
    {
        return statusId;
    }

                                              
    /**
     * Set the value of StatusId
     *
     * @param v new value
     */
    public void setStatusId(int v) throws TorqueException
    {
    
                  if (this.statusId != v)
              {
            this.statusId = v;
            setModified(true);
        }
    
          
                                  
                  // update associated Task
        if (collTasks != null)
        {
            for (int i = 0; i < collTasks.size(); i++)
            {
                ((Task) collTasks.get(i))
                    .setStatusId(v);
            }
        }
                                }
          
    /**
     * Get the Name
     *
     * @return String
     */
    public String getName()
    {
        return name;
    }

                        
    /**
     * Set the value of Name
     *
     * @param v new value
     */
    public void setName(String v) 
    {
    
                  if (!ObjectUtils.equals(this.name, v))
              {
            this.name = v;
            setModified(true);
        }
    
          
              }
          
    /**
     * Get the SortOrder
     *
     * @return int
     */
    public int getSortOrder()
    {
        return sortOrder;
    }

                        
    /**
     * Set the value of SortOrder
     *
     * @param v new value
     */
    public void setSortOrder(int v) 
    {
    
                  if (this.sortOrder != v)
              {
            this.sortOrder = v;
            setModified(true);
        }
    
          
              }
          
    /**
     * Get the Image
     *
     * @return String
     */
    public String getImage()
    {
        return image;
    }

                        
    /**
     * Set the value of Image
     *
     * @param v new value
     */
    public void setImage(String v) 
    {
    
                  if (!ObjectUtils.equals(this.image, v))
              {
            this.image = v;
            setModified(true);
        }
    
          
              }
  
         
                                
            
          /**
     * Collection to store aggregation of collTasks
     */
    protected List<Task> collTasks;

    /**
     * Temporary storage of collTasks to save a possible db hit in
     * the event objects are add to the collection, but the
     * complete collection is never requested.
     */
    protected void initTasks()
    {
        if (collTasks == null)
        {
            collTasks = new ArrayList<Task>();
        }
    }

        
    /**
     * Method called to associate a Task object to this object
     * through the Task foreign key attribute
     *
     * @param l Task
     * @throws TorqueException
     */
    public void addTask(Task l) throws TorqueException
    {
        getTasks().add(l);
        l.setStatus((Status) this);
    }

    /**
     * The criteria used to select the current contents of collTasks
     */
    private Criteria lastTasksCriteria = null;
      
    /**
                   * If this collection has already been initialized, returns
     * the collection. Otherwise returns the results of
     * getTasks(new Criteria())
                   *
     * @return the collection of associated objects
           * @throws TorqueException
           */
    public List<Task> getTasks()
              throws TorqueException
          {
                      if (collTasks == null)
        {
            collTasks = getTasks(new Criteria(10));
        }
                return collTasks;
          }

    /**
           * If this collection has already been initialized with
     * an identical criteria, it returns the collection.
     * Otherwise if this Status has previously
           * been saved, it will retrieve related Tasks from storage.
     * If this Status is new, it will return
     * an empty collection or the current collection, the criteria
     * is ignored on a new object.
     *
     * @throws TorqueException
     */
    public List<Task> getTasks(Criteria criteria) throws TorqueException
    {
              if (collTasks == null)
        {
            if (isNew())
            {
               collTasks = new ArrayList<Task>();
            }
            else
            {
                        criteria.add(TaskPeer.STATUS_ID, getStatusId() );
                        collTasks = TaskPeer.doSelect(criteria);
            }
        }
        else
        {
            // criteria has no effect for a new object
            if (!isNew())
            {
                // the following code is to determine if a new query is
                // called for.  If the criteria is the same as the last
                // one, just return the collection.
                            criteria.add(TaskPeer.STATUS_ID, getStatusId());
                            if (!lastTasksCriteria.equals(criteria))
                {
                    collTasks = TaskPeer.doSelect(criteria);
                }
            }
        }
        lastTasksCriteria = criteria;

        return collTasks;
          }

    /**
           * If this collection has already been initialized, returns
     * the collection. Otherwise returns the results of
     * getTasks(new Criteria(),Connection)
           * This method takes in the Connection also as input so that
     * referenced objects can also be obtained using a Connection
     * that is taken as input
     */
    public List<Task> getTasks(Connection con) throws TorqueException
    {
              if (collTasks == null)
        {
            collTasks = getTasks(new Criteria(10), con);
        }
        return collTasks;
          }

    /**
           * If this collection has already been initialized with
     * an identical criteria, it returns the collection.
     * Otherwise if this Status has previously
           * been saved, it will retrieve related Tasks from storage.
     * If this Status is new, it will return
     * an empty collection or the current collection, the criteria
     * is ignored on a new object.
     * This method takes in the Connection also as input so that
     * referenced objects can also be obtained using a Connection
     * that is taken as input
     */
    public List<Task> getTasks(Criteria criteria, Connection con)
            throws TorqueException
    {
              if (collTasks == null)
        {
            if (isNew())
            {
               collTasks = new ArrayList<Task>();
            }
            else
            {
                         criteria.add(TaskPeer.STATUS_ID, getStatusId());
                         collTasks = TaskPeer.doSelect(criteria, con);
             }
         }
         else
         {
             // criteria has no effect for a new object
             if (!isNew())
             {
                 // the following code is to determine if a new query is
                 // called for.  If the criteria is the same as the last
                 // one, just return the collection.
                             criteria.add(TaskPeer.STATUS_ID, getStatusId());
                             if (!lastTasksCriteria.equals(criteria))
                 {
                     collTasks = TaskPeer.doSelect(criteria, con);
                 }
             }
         }
         lastTasksCriteria = criteria;

         return collTasks;
           }

                  
              
                    
                              
                                
                                                              
                                        
                    
                    
          
    /**
                 * If this collection has already been initialized with
     * an identical criteria, it returns the collection.
     * Otherwise if this Status is new, it will return
                 * an empty collection; or if this Status has previously
     * been saved, it will retrieve related Tasks from storage.
     *
     * This method is protected by default in order to keep the public
     * api reasonable.  You can provide public methods for those you
     * actually need in Status.
     */
    protected List getTasksJoinStatus(Criteria criteria)
        throws TorqueException
    {
                    if (collTasks == null)
        {
            if (isNew())
            {
               collTasks = new ArrayList<Task>();
            }
            else
            {
                              criteria.add(TaskPeer.STATUS_ID, getStatusId());
                              collTasks = TaskPeer.doSelectJoinStatus(criteria);
            }
        }
        else
        {
            // the following code is to determine if a new query is
            // called for.  If the criteria is the same as the last
            // one, just return the collection.
                                    criteria.add(TaskPeer.STATUS_ID, getStatusId());
                                    if (!lastTasksCriteria.equals(criteria))
            {
                collTasks = TaskPeer.doSelectJoinStatus(criteria);
            }
        }
        lastTasksCriteria = criteria;

        return collTasks;
                }
                            


          
    private static List<String> fieldNames = null;

    /**
     * Generate a list of field names.
     *
     * @return a list of field names
     */
    public static synchronized List getFieldNames()
    {
        if (fieldNames == null)
        {
            fieldNames = new ArrayList<String>();
              fieldNames.add("StatusId");
              fieldNames.add("Name");
              fieldNames.add("SortOrder");
              fieldNames.add("Image");
              fieldNames = Collections.unmodifiableList(fieldNames);
        }
        return fieldNames;
    }

    /**
     * Retrieves a field from the object by name passed in as a String.
     *
     * @param name field name
     * @return value
     */
    public Object getByName(String name)
    {
          if (name.equals("StatusId"))
        {
                return new Integer(getStatusId());
            }
          if (name.equals("Name"))
        {
                return getName();
            }
          if (name.equals("SortOrder"))
        {
                return new Integer(getSortOrder());
            }
          if (name.equals("Image"))
        {
                return getImage();
            }
          return null;
    }

    /**
     * Retrieves a field from the object by name passed in
     * as a String.  The String must be one of the static
     * Strings defined in this Class' Peer.
     *
     * @param name peer name
     * @return value
     */
    public Object getByPeerName(String name)
    {
          if (name.equals(StatusPeer.STATUS_ID))
        {
                return new Integer(getStatusId());
            }
          if (name.equals(StatusPeer.NAME))
        {
                return getName();
            }
          if (name.equals(StatusPeer.SORT_ORDER))
        {
                return new Integer(getSortOrder());
            }
          if (name.equals(StatusPeer.IMAGE))
        {
                return getImage();
            }
          return null;
    }

    /**
     * Retrieves a field from the object by Position as specified
     * in the xml schema.  Zero-based.
     *
     * @param pos position in xml schema
     * @return value
     */
    public Object getByPosition(int pos)
    {
            if (pos == 0)
        {
                return new Integer(getStatusId());
            }
              if (pos == 1)
        {
                return getName();
            }
              if (pos == 2)
        {
                return new Integer(getSortOrder());
            }
              if (pos == 3)
        {
                return getImage();
            }
              return null;
    }
     
    /**
     * Stores the object in the database.  If the object is new,
     * it inserts it; otherwise an update is performed.
     *
     * @throws Exception
     */
    public void save() throws Exception
    {
          save(StatusPeer.getMapBuilder()
                .getDatabaseMap().getName());
      }

    /**
     * Stores the object in the database.  If the object is new,
     * it inserts it; otherwise an update is performed.
       * Note: this code is here because the method body is
     * auto-generated conditionally and therefore needs to be
     * in this file instead of in the super class, BaseObject.
       *
     * @param dbName
     * @throws TorqueException
     */
    public void save(String dbName) throws TorqueException
    {
        Connection con = null;
          try
        {
            con = Transaction.begin(dbName);
            save(con);
            Transaction.commit(con);
        }
        catch(TorqueException e)
        {
            Transaction.safeRollback(con);
            throw e;
        }
      }

      /** flag to prevent endless save loop, if this object is referenced
        by another object which falls in this transaction. */
    private boolean alreadyInSave = false;
      /**
     * Stores the object in the database.  If the object is new,
     * it inserts it; otherwise an update is performed.  This method
     * is meant to be used as part of a transaction, otherwise use
     * the save() method and the connection details will be handled
     * internally
     *
     * @param con
     * @throws TorqueException
     */
    public void save(Connection con) throws TorqueException
    {
          if (!alreadyInSave)
        {
            alreadyInSave = true;


  
            // If this object has been modified, then save it to the database.
            if (isModified())
            {
                if (isNew())
                {
                    StatusPeer.doInsert((Status) this, con);
                    setNew(false);
                }
                else
                {
                    StatusPeer.doUpdate((Status) this, con);
                }
                }

                                      
                                    if (collTasks != null)
            {
                for (int i = 0; i < collTasks.size(); i++)
                {
                    ((Task) collTasks.get(i)).save(con);
                }
            }
                                  alreadyInSave = false;
        }
      }

                        
      /**
     * Set the PrimaryKey using ObjectKey.
     *
     * @param key statusId ObjectKey
     */
    public void setPrimaryKey(ObjectKey key)
        throws TorqueException
    {
            setStatusId(((NumberKey) key).intValue());
        }

    /**
     * Set the PrimaryKey using a String.
     *
     * @param key
     */
    public void setPrimaryKey(String key) throws TorqueException
    {
            setStatusId(Integer.parseInt(key));
        }

  
    /**
     * returns an id that differentiates this object from others
     * of its class.
     */
    public ObjectKey getPrimaryKey()
    {
          return SimpleKey.keyFor(getStatusId());
      }
 

    /**
     * Makes a copy of this object.
     * It creates a new object filling in the simple attributes.
       * It then fills all the association collections and sets the
     * related objects to isNew=true.
       */
      public Status copy() throws TorqueException
    {
        return copyInto(new Status());
    }
  
    protected Status copyInto(Status copyObj) throws TorqueException
    {
          copyObj.setStatusId(statusId);
          copyObj.setName(name);
          copyObj.setSortOrder(sortOrder);
          copyObj.setImage(image);
  
                            copyObj.setStatusId( 0);
                              
                                      
                            
        List v = getTasks();
                            if (v != null)
        {
            for (int i = 0; i < v.size(); i++)
            {
                Task obj = (Task) v.get(i);
                copyObj.addTask(obj.copy());
            }
        }
        else
        {
            copyObj.collTasks = null;
        }
                            return copyObj;
    }

    /**
     * returns a peer instance associated with this om.  Since Peer classes
     * are not to have any instance attributes, this method returns the
     * same instance for all member of this class. The method could therefore
     * be static, but this would prevent one from overriding the behavior.
     */
    public StatusPeer getPeer()
    {
        return peer;
    }

  
    /**
     * Creates a StatusBean with the contents of this object
       * This also creates beans for cached related objects, if they exist
       * @return a StatusBean with the contents of this object
     */
    public StatusBean getBean()
    {
        return getBean(new IdentityMap());
    }

    /**
     * Creates a StatusBean with the contents of this object
     * intended for internal use only
     * @param createdBeans a IdentityMap which maps objects
     *        to already created beans
     * @return a StatusBean with the contents of this object
     */
    public StatusBean getBean(IdentityMap createdBeans)
    {
        StatusBean result = (StatusBean) createdBeans.get(this);
        if (result != null ) {
            // we have already created a bean for this object, return it
            return result;
        }
        // no bean exists for this object; create a new one
        result = new StatusBean();
        createdBeans.put(this, result);

          result.setStatusId(getStatusId());
          result.setName(getName());
          result.setSortOrder(getSortOrder());
          result.setImage(getImage());
  
                                                        
                    
                  if (collTasks != null)
        {
            List<TaskBean> relatedBeans = new ArrayList<TaskBean>(collTasks.size());
            for (Iterator collTasksIt = collTasks.iterator(); collTasksIt.hasNext(); )
            {
                Task related = (Task) collTasksIt.next();
                TaskBean relatedBean = related.getBean(createdBeans);
                relatedBeans.add(relatedBean);
            }
            result.setTaskBeans(relatedBeans);
        }
                  
                  result.setModified(isModified());
        result.setNew(isNew());
        return result;
    }

    /**
     * Creates an instance of Status with the contents
     * of a StatusBean.
     * This behaviour could have also been achieved using a constructor,
     * however as this class is abstract no constructors are allowed
     * @param bean the StatusBean which contents are used to create
     *        the resulting class
     * @return an instance of Status with the contents of bean
     */
    public static Status createStatus(StatusBean bean)
        throws TorqueException
    {
        return createStatus(bean, new IdentityMap());
    }

    /**
     * Creates an instance of Status with the contents
     * of a StatusBean.
     * This behaviour could have also been achieved using a constructor,
     * however as this class is abstract no constructors are allowed.
     *
     * This method is intended for internal use only.
     * @param bean the StatusBean which contents are used to create
     *        the resulting class
     * @param createdObjects a IdentityMap which maps beans
     *        to already created objects
     * @return an instance of Status with the contents of bean
     */

    public static Status createStatus(StatusBean bean, IdentityMap createdObjects)
        throws TorqueException
    {
        Status result = (Status) createdObjects.get(bean);
        if (result != null)
        {
            // we already have an object for the bean, return it
            return result;
        }
        result = new Status();
        createdObjects.put(bean, result);

          result.setStatusId(bean.getStatusId());
          result.setName(bean.getName());
          result.setSortOrder(bean.getSortOrder());
          result.setImage(bean.getImage());
  
                                                        
                    
        {
            List relatedBeans = bean.getTaskBeans();
            if (relatedBeans != null)
            {
                for (Iterator relatedBeansIt = relatedBeans.iterator(); relatedBeansIt.hasNext(); )
                {
                    TaskBean relatedBean = (TaskBean) relatedBeansIt.next();
                    Task related = Task.createTask(relatedBean, createdObjects);
                    result.addTaskFromBean(related);
                }
            }
        }
                  
              result.setModified(bean.isModified());
    result.setNew(bean.isNew());
  	return result;
    }

                                                        
                    
    /**
     * Method called to associate a Task object to this object.
     * through the Task foreign key attribute
     *
     * @param toAdd Task
     */
    protected void addTaskFromBean(Task toAdd)
    {
        initTasks();
        collTasks.add(toAdd);
    }
                    

    public String toString()
    {
        StringBuffer str = new StringBuffer();
        str.append("Status:\n");
        str.append("StatusId = ")
               .append(getStatusId())
             .append("\n");
        str.append("Name = ")
               .append(getName())
             .append("\n");
        str.append("SortOrder = ")
               .append(getSortOrder())
             .append("\n");
        str.append("Image = ")
               .append(getImage())
             .append("\n");
        return(str.toString());
    }
}
