<?php

namespace dominion\file;

/**
 * This is the model class for table "file_config".
 *
 * @property int $id
 * @property string $module
 * @property string $type
 * @property int $height
 * @property int $width
 * @property string $name
 * @property int $crop
 * @property int $cut
 * @property int $addBorder
 * @property int $fileId Шаблон изображения
 * @property int $border_top отступы для окна внутри шаблона (сверху)
 * @property int $border_right отступы для окна внутри шаблона (справа)
 * @property int $border_left отступы для окна внутри шаблона (слева)
 * @property int $border_bottom отступы для окна внутри шаблона (снизу)
 * @property int $quality качество (степень сжатия)
 */
class Config extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'file_config';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['module', 'type'], 'required'],
            [['height', 'width', 'cut', 'crop', 'addBorder', 'fileId', 'border_top', 'border_right', 'border_left', 'border_bottom', 'quality'], 'integer'],
            [['module', 'type'], 'string', 'max' => 50],
            [['name'], 'string', 'max' => 500],
            [['fileId'], 'formatImg'],
        ];
    }
    public function formatImg($attribute, $params)
    {
        File::validateFormat($this, $attribute, ['extensions' => 'png, jpg']);
    }

    /**
     * {@inheritdoc}
     */
    /*public function attributeLabels()
    {
        return [
            'id' => Module::t('app', 'ID'),
            'module' => Module::t('app', 'Module'),
            'type' => Module::t('app', 'Type'),
            'height' => Module::t('app', 'Height'),
            'width' => Module::t('app', 'Width'),
            'name' => Module::t('app', 'Name'),
            'crop' => Module::t('app', 'Crop'),
            'cut' => Module::t('app', 'Cut'),
            'addBorder' => Module::t('app', 'Add Border'),
            'fileId' => Module::t('app', 'File'),
            'border_right' => Module::t('app', 'Border Right'),
            'border_top' => Module::t('app', 'Border Top'),
            'border_left' => Module::t('app', 'Border Left'),
            'border_bottom' => Module::t('app', 'Border Bottom'),
            'quality' => Module::t('app', 'Quality'),
        ];
    }*/

    /*public function beforeSave($insert)
    {
        $this->fileId = File::formSave('config', $this->fileId);
        return parent::beforeSave($insert);
    }*/

    public function getFile()
    {
        return $this->hasOne(File::className(), ['id' => 'fileId']);
    }

    public static function getData($params, $root)
    {
        $query = self::find();
        $root->andWhere($query, $params, ['id', 'module', 'type']);
        $root->andWhereLike($query, $params, ['name']);

        $root->setMetaByQuery($query);
        $root->orderBy($query, $params, ['id', 'module', 'type', 'height', 'width', 'name', 'crop', 'cut', 'addBorder']);
        return $root->getItemsByPage($query);
    }

    public function beforeDelete()
    {
        if($this->file)
        {
            $this->file->delete();
        }
        return parent::beforeDelete();
    }

    public function customSave($args)
    {
        if((isset($args['fileDelete']) && $args['fileDelete']) || (isset($args['file'], $args['fileName']) && !empty($args['file'])))
        {
            if($this->file)
            {
                $this->file->delete();
            }
        }
        foreach(['name', 'module', 'type', 'height', 'width', 'cut', 'crop', 'addBorder', 'border_top', 'border_right', 'border_left', 'border_bottom', 'quality'] as $item)
        {
            if(isset($args[$item]))
            {
                $this->$item =  is_bool($args[$item]) ? (int) $args[$item] : $args[$item];
            }
        }

        if((isset($args['file'], $args['fileName']) && !empty($args['file'])))
        {
            $this->fileId = File::saveBase64File('file', $args['file'], $args['fileName'], '', false);
        }
        $this->fileId = (int)$this->fileId;
        $this->save();
        return $this->id;
    }

    public function resize($args)
    {
        $time = time() + 5;
        $all = isset($args['all']) && $args['all'];
        $fileId = isset($args['fileId']) ? $args['fileId'] : 0;
        $files =  File::find()->andWhere(['module'=> $this->module])->andWhere(['>', 'id', $fileId])->limit(200)->all();
        $output = ['count' => 0];
        $fileTemplate = $this->file ? [
            'filePatch' => $this->file->getFilePath(false, true),
            'border_top' => $this->border_top,
            'border_right' => $this->border_right,
            'border_left' => $this->border_left,
            'border_bottom' => $this->border_bottom,
        ] : [];
        if($this->file)
        {
            $this->file->downloadOriginal();
        }


        if(!empty($files))
        {
            $output['step'] = 'procccess';
            foreach ($files as $file)
            {
                try{
                    $file->downloadOriginal();
                    $file->resize($this->type, $this->height, $this->width, $this->crop, $this->cut, $this->addBorder, $all, $fileTemplate, $this->quality);
                    if($file->cropFile)
                    {
                        @unlink($file->cropFile);
                    }
                    if(\Yii::$app->has('s3'))
                    {
                        $s3 = \Yii::$app->get('s3');
                        if(file_exists($file->getFilePath($this->type, true)))
                        {
                            $s3->upload($file->getFilePath($this->type), $file->getFilePath($this->type, true));
                            @unlink($file->getFilePath($this->type, true));
                        }
                    }
                }
                catch (\Exception $ex)
                {
                }
                $output['fileId'] = $file->id;
                $output['count'] ++;
                if($time < time())
                {
                    break;
                }
            }
        }
        else
        {
            $output['step'] = 'finish';
        }
        return $output;

    }
}