<?php

namespace Velis\Bpm\Currency;

use Velis\Model\DataObject;
use Velis\Model\Cacheable;
use Velis\Arrays;
use Velis\Lang;
use Exception;

/**
 * Currency rate type model
 * @author Olek Procki <olo@velis.pl>
 */
class RateType extends DataObject implements Cacheable
{
    const NBP_MEAN  = 'NBPMean';
    const NBP_SALES = 'NBPSales';


    /**
     * Default currecy rate type
     * @var \Velis\Bpm\Currency\RateType
     */
    protected static $_default;


    /**
     * Returns related table name
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.currency_rate_type_tab';
    }


    /**
     * Returns currency rate type name
     * @return string
     */
    public function getName()
    {
        return $this['name'];
    }


    /**
     * Returns default currency rate type for application
     * @return \Velis\Bpm\Currency\RateType
     */
    public static function getDefault()
    {
        if (!isset(self::$_default)) {
            self::$_default = Arrays::find(self::listCached(), 'is_default', 1);
        }
        return self::$_default;
    }


    /**
     * Returns default currency rate type id
     * @return string
     */
    public static function getDefaultId()
    {
        if ($default = self::getDefault()) {
            return $default->id();
        }
        return self::NBP_MEAN;
    }


    /**
     * Removes currency rate type
     *
     * @return bool
     * @throws Exception
     */
    public function remove()
    {
        if (in_array($this->id(), [self::NBP_MEAN, self::NBP_SALES])) {
            throw new Exception(Lang::get('GENERAL_DATA_CANT_BE_DELETED'));
        }
        return parent::_remove();
    }
}
