<?php

  /**
   * Framework level currencies management implementation
   * 
   * @package angie.frameworks.globalization
   * @subpackage models
   */
  class FwCurrencies extends BaseCurrencies {
    
    /**
     * Returns true if $user can create new currency
     * 
     * @param IUser $user
     * @return boolean
     */
    static function canAdd(IUser $user) {
      return $user->isAdministrator();
    } // canAdd
    
    // ---------------------------------------------------
    //  Finders
    // ---------------------------------------------------
    
    /**
     * Cached default currency
     *
     * @var Currency
     */
    static private $default_currency = false;
  
    /**
     * Return default currency
     *
     * @return Currency
     */
    static function getDefault() {
      if(self::$default_currency === false) {
        self::$default_currency = Currencies::find(array(
          'order' => 'is_default DESC',
          'one' => true,
        ));
      } //if
      
      return self::$default_currency;
    } // findDefault
    
    /**
     * Set $currency as default
     *
     * @param Currency $currency
     * @return Currency
     */
    static function setDefault(Currency $currency) {
      if($currency->getIsDefault()) {
        return true;
      } // if
      
      try {
        DB::beginWork('Setting default currency @ ' . __CLASS__);
      
        $currency->setIsDefault(true);
        $currency->save();
        
        DB::execute('UPDATE ' . TABLE_PREFIX . 'currencies SET is_default = ? WHERE id != ?', false, $currency->getId());
        cache_remove_by_pattern(TABLE_PREFIX . 'currencies_id_*');
        
        DB::commit('Default currency set @ ' . __CLASS__);
        
        self::$default_currency = $currency;
      } catch(Exception $e) {
        DB::rollback('Failde to set default currency @ ' . __CLASS__);
        throw $e;
      } // try
      
      return self::$default_currency;
    } // setDefault
    
    /**
     * Return ID of default currency
     * 
     * @return integer
     */
    static function getDefaultId() {
      if(self::$default_currency instanceof Currency) {
        return self::$default_currency->getId();
      } else {
        return (integer) DB::executeFirstCell('SELECT id FROM ' . TABLE_PREFIX . 'currencies ORDER BY is_default DESC LIMIT 0, 1');
      } // if
    } // getDefaultId
    
    /**
  	 * Return currencies slice based on given criteria
  	 * 
  	 * @param integer $num
  	 * @param array $exclude
  	 * @param integer $timestamp
  	 * @return DBResult
  	 */
  	static function getSlice($num = 10, $exclude = null, $timestamp = null) {
  		if($exclude) {
  			return Currencies::find(array(
  			  'conditions' => array("id NOT IN (?)", $exclude), 
  			  'order' => 'name', 
  			  'limit' => $num,  
  			));
  		} else {
  			return Currencies::find(array(
  			  'order' => 'name', 
  			  'limit' => $num,  
  			));
  		} // if
  	} // getSlice
  	
  	/**
  	 * Return currency by currency code
  	 * 
  	 * @param string $code
  	 * @return Currency
  	 */
  	static function findByCode($code) {
  	  return Currencies::find(array(
  	    'conditions' => array('code = ?', $code), 
  	    'one' => true, 
  	  ));
  	} // findByCode
  	
  	/**
  	 * Cached ID name map
  	 *
  	 * @var array
  	 */
  	static private $id_name_map = false;
  	
  	/**
  	 * Return ID name map of currencies
  	 * 
  	 * @return array
  	 */
  	static function getIdNameMap() {
  	  if(self::$id_name_map === false) {
        $cached_values = cache_get("currencies_id_name_map");
        if ($cached_values) {
          self::$id_name_map = $cached_values;
        } else {
          $rows = DB::execute('SELECT id, name FROM ' . TABLE_PREFIX . 'currencies ORDER BY name');
          if($rows) {
            self::$id_name_map = array();

            foreach($rows as $row) {
              self::$id_name_map[(integer) $row['id']] = $row['name'];
            } // foreach
          } else {
            self::$id_name_map = null;
          } // if

          cache_set("currencies_id_name_map", self::$id_name_map);
        } // if
  	  } // if
  	  
  	  return self::$id_name_map;
  	} // getIdNameMap
  	
  	/**
  	 * Cached ID details map
  	 *
  	 * @var array
  	 */
  	static private $id_details_map = false;
  	
  	/**
  	 * Prepare and return ID details map
  	 * 
  	 * @return array
  	 */
  	static function getIdDetailsMap() {
  	  if(self::$id_details_map === false) {
        $cached_values = cache_get("currencies_id_details_map");
        if ($cached_values) {
          self::$id_details_map = $cached_values;
        } else {
          $currencies = Currencies::find();

          if($currencies) {
            self::$id_details_map = array();

            foreach(Currencies::find() as $currency) {
              self::$id_details_map[$currency->getId()] = array(
                'name' => $currency->getName(),
                'code' => $currency->getCode(),
              );
            } // foreach
          } else {
            self::$id_details_map = null;
          } // if

          cache_set("currencies_id_details_map", self::$id_details_map);
        } // if
  	  } // if
  	  
  	  return self::$id_details_map;
  	} // getIdDetailsMap
    
  }