<?php

  /**
   * Framework level homescreens manager implementation
   * 
   * @package angie.frameworks.homescreens
   * @subpackage models
   */
  abstract class FwHomescreens extends BaseHomescreens {
    
    /**
     * Cached default home screen instance
     *
     * @var Homescreen
     */
    private static $default_homescreen = false;
    
    /**
     * Return default home screen
     * 
     * @return Homescreen
     */
    static function findDefault() {
      if(self::$default_homescreen === false) {
        self::$default_homescreen = Homescreens::find(array(
          'conditions' => 'parent_type IS NULL AND parent_id IS NULL', 
          'one' => true, 
        ));
      } // if
      
      return self::$default_homescreen;
    } // findDefault
    
    /**
     * Cached default home screen ID
     *
     * @var integer
     */
    private static $default_homescreen_id = false;
    
    /**
     * Return ID of default home screen
     * 
     * @return integer
     */
    static function findDefaultId() {
      if(self::$default_homescreen_id === false) {
        if(self::$default_homescreen instanceof Homescreen) {
          self::$default_homescreen_id = self::$default_homescreen->getId();
        } else {
          self::$default_homescreen_id = (integer) DB::executeFirstCell('SELECT id FROM ' . TABLE_PREFIX . 'homescreens WHERE parent_type IS NULL AND parent_id IS NULL LIMIT 0, 1');
        } // if
      } // if
      
      return self::$default_homescreen_id;
    } // findDefaultId
    
    /**
     * Return home screen by parent object
     * 
     * @param IHomescreen $parent
     * @return Homescreen
     */
    static function findByParent($parent) {
      if($parent instanceof IHomescreen) {
        return Homescreens::find(array(
          'conditions' => array('parent_type = ? AND parent_id = ?', get_class($parent), $parent->getId()), 
          'one' => true, 
        ));
      } elseif($parent === null) {
        return Homescreens::findDefault();
      } else {
        throw new InvalidInstanceError('parent', $parent, 'IHomescreen');
      } // if
    } // findByParent
  
  }