<?php

/**
 * GenreTable
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 */
class GenreTable extends Doctrine_Table
{
  /**
   * Returns an instance of this class.
   *
   * @return object GenreTable
   */
  public static function getInstance()
  {
      return Doctrine_Core::getTable('Genre');
  }

  /**
   * Add a custom genre to the database or get its key if it exists
   * @param name str: the name of the genre to add
   * @return     int: the primary key added or found
   */
  public function addGenre( $name )
  {
    //trim whitespace
    $name = trim($name);
    
    if( empty( $name ) )
    {
      $name = 'Uncategorized';
    }
    
    //is this name already in the collection?
    if( is_numeric( $name ) && $name < 127 )
    {
      $result = $this->find( $name );
    }
    
    if( is_numeric( $name ) && $name > 126 )
    {
      $name = 'Uncategorized';
    }
  
    $q = Doctrine_Query::create()
      ->select( 'g.id' )
      ->from( 'Genre g' )
      ->where( 'g.name = ?', $name);
    $result = $q->fetchOne();
     
    if ( is_object( $result ) && $result->id > 0 )
    {
      $retId = $result->id;
      unset($q, $result);
      return $retId;
    }
    else
    {
      $item = new Genre;
      $item->name = $name;
      $item->save();
      $id = $item->getId();
      $item->free();
      unset($item, $q, $result);
      
      return $id;
    }
  }
  
  /**
   * Remove album records with no song relation
   *
   * @return             array: number of records removed
   */
  public function finalizeScan()
  {
    $q = Doctrine_Query::create()
      ->delete('Genre g')
      ->where('g.id NOT IN (SELECT sg.genre_id FROM SongGenres AS sg)')
      ->andWhere( 'g.id > 126' )
      ->execute();
    return $q;
  }
}