<?php

class Firmware extends PhonalisaRecord
{

    public $id;
    public $version;
    public $data;
    public $phoneType;
    public $standard;
    public $fileName;

    public static function myAttributes()
    {
        return array(
            'id' => 'id',
            'version' => 'version',
            'phoneType' => 'phoneType',
            'data' => 'data',
            'standard' => 'standard',
            'fileName' => 'fileName',
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Gateway the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'firmware';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('data', 'required', 'on' => 'create'),
            array('data', 'validateFirmware', 'on' => 'create'),
            array('data', 'validateFirmware', 'on' => 'update'),
            //array('fileName', 'ext.PhonalisaValidators.isUnique'),
            array('id, version, data, phoneType, standard, fileName', 'safe')//FIXME ! 
        );
    }

    //NOTE $fileTempPath for second Validation after send the Post:
    public function validateFirmware($attribute, $params, $fileTmpPath = NULL)
    {
        $phone = PhoneModelFactory::getPhoneModelOfType($this->phoneType);
        if ($phone == NULL) {
            $this->addError($attribute, __("FIRMWARE_VALIDATION_ERROR_NO_VALID_PHONE_MODEL_FOUND"));
            return false;
        }

        $filename = $this->$attribute;

        $model = $this->findByAttributes(array('fileName' => $filename, 'phoneType' => $this->phoneType));

        if ($model) {

            if ($this->isNewRecord()) {
                $this->addError($attribute, __('FIRMWARE_VALIDATION_ERROR_FILE_EXISTS'));
                return false;
            } else if ($model->id !== $this->id) {

                $this->addError($attribute, __('FIRMWARE_VALIDATION_ERROR_FILE_EXISTS'));
                return false;
            }
        }

        $errorText = "";
        $firmWareVersion = $phone->validateFirmwareFile($filename, $fileTmpPath, $errorText);
        if ($firmWareVersion === false) {
            $this->addError($attribute, $errorText);
            return false;
        } else if ($firmWareVersion === true) {
            return true;
        }
        return $firmWareVersion;
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array();
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            //'id'=>'id',
            'version' => __('FIRMWARE_MODEL_VERSION'),
            'data' => __('FIRMWARE_MODEL_DATA'),
            'phoneType' => __('FIRMWARE_MODEL_PHONE_TYPE'),
            'standard' => __('FIRMWARE_MODEL_STANDARD'),
            'fileName' => __('FIRMWARE_MODEL_FILE_NAME'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CPhonalisaDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search($order = 'version')
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        $filter = $this->getFilter($criteria, $order);

        $filter['pagination'] = array(
            'pageSize' => getGridPageSize('firmware-grid'),
        );

        if ($filter != null) {
            return new CPhonalisaDataProvider($this, $filter
            );
        }
    }

    public function afterSave()
    {
        if ($this->standard == true) {
            $oldStandardModels = $this->findAllByAttributes(array('phoneType' => $this->phoneType, 'standard' => $this->standard));
            foreach ($oldStandardModels as $oldStandardModel) {
                if ($oldStandardModel && $oldStandardModel->id != $this->id) {
                    $oldStandardModel->scenario = 'afterSave';
                    $oldStandardModel->standard = '0';
                    if (!$oldStandardModel->save()) {
                        dump($oldStandardModel->errors);
                    }
                }
            }
        }
        if ($this->scenario != 'afterSave') {
            if (!empty($_FILES['Firmware']['tmp_name']['data'])) {
                $file = CUploadedFile::getInstance($this, 'data');
                if ($file->tempName != '') {
                    $this->saveFileToFieldByPath("data", $file->tempName);
                }
            }
        }
        return parent::afterSave();
    }

    public function beforeDelete()
    {
        if (!$this->deleteBinaryField("data", '', 0)) {
            Log::w('Could not delete file "' . $this->id . '.bin"', 'phonalisa-firmware');
        }
        return parent::beforeDelete();
    }
}
