<?php

/**
 * @param ExtCode singleton
 * @author p.treu
 *
 */
class ExtCode extends ActiveRecord {

    const NULL_EXT_CODE = "-";

    /**
     * 
     * @param system $className
     * @return ExtCode
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * (non-PHPdoc)
     * @see CActiveRecord::tableName()
     */
    public function tableName() {
        return 'ext_code';
    }

    /**
     * 
     * @throws CException
     * @return ExtCode
     */
    public function getSingleton() {
        $models = ExtCode::model()->findAll();
        if (count($models) == 0)
            throw new CException(Yii::t('app', 'ExtCode table is empty.'));
        if (count($models) > 1)
            throw new CException(Yii::t('app', 'ExtCode table should not have more than one row.'));

        return $models[0];
    }

    public static function acquireAccess() {
        $models = ExtCode::model()->findAll();
        return ($models[0]->updateAll(array('updating' => 1), 'updating = 0') != 0);
    }
    public static function releaseAccess() {
        $models = ExtCode::model()->findAll();
        return ($models[0]->updateAll(array('updating' => 0), 'updating = 1') != 0);
    }
    public static function generateNewCode() {
        $models = ExtCode::model()->findAll();
        $models[0]->free_code += 1;
        $models[0]->save();
        return $models[0]->free_code;
    }

}
