<?php

namespace app\models\base;

use app\models\StoryImages;
use app\models\TopicImages;
use Yii;
use app\components\behaviors\CachedBehavior;

/**
 * This is the model class for table "story".
 *
 * @property int $id
 * @property int|null $topic_id
 * @property string|null $title
 * @property string $meta_title
 * @property string $url
 * @property string|null $keywords
 * @property string $description
 * @property int $order
 * @property int $active
 * @property string $show
 * @property string $ext
 */
class Story extends BaseFrontendClass
{

	/*
	 * Ключи кэширования для авто сброса
	 */
	public static $keysCache=[
		'archive_rubrics-Story-##'	=>600,
		'archive_news-Story-##'		=>60,
		'archive_rubrics-Story-'   	=>600,
		'archive_news-Story-'		=>60
	];


	/**
     * @var string
     */
    public $photo;
	public static $story_dir = 'story-images';

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'story';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['topic_id', 'order', 'active'], 'integer'],
            [['meta_title', 'url', 'description', 'title'], 'required'],
            [['keywords', 'show', 'ext'], 'string'],
            [['title'], 'string', 'max' => 255],
            [['meta_title'], 'string', 'max' => 70],
            [['url'], 'string', 'max' => 128],
            [['description'], 'string', 'max' => 300],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'topic_id' => 'Topic ID',
            'title' => 'Title',
            'meta_title' => 'Meta Title',
            'url' => 'Url',
            'keywords' => 'Keywords',
            'description' => 'Description',
            'order' => 'Order',
            'active' => 'Active',
            'show' => 'Show',
            'ext' => 'Ext',
        ];
    }

    /**
     * {@inheritdoc}
     * @return StoryQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new StoryQuery(get_called_class());
    }
    /**
     * {@inheritdoc}
     * @return StoryQuery the active query used by this AR class.
     */

	public function GetById($id)
    {
        return $this->find()->andWhere(['id'=>$id])->one();
    }

	public function beforeSave($insert)
	{
		if (!parent::beforeSave($insert)) {
			return false;
		}
		if( is_int($this->show) ){
			$this->show = ($this->show == 1)?'Y':'N';
		}
		return true;
	}

    /**
     * {@inheritdoc}
     * @return status.
     */

	public function del($id)
    {
		if( Yii::$app->user->can('admin') ){
			$name = basename($id."_*.*");
			$file = Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";

			foreach (glob("$file") as $filename) {
				unlink($filename);
			}
			// to do удалить связи то же надобудет
			$this->delete();
		}
	}

	/**
     * {@inheritdoc}
     * @return status.
     */

	public function Show($id, $state = -1)
    {
		if( $state < 0 ){
			$this->show = ($this->show == 'Y')?'N':'Y';
		}else{
			$this->show = $state;
		}
		return $this->save();
	}

	/**
     * {@inheritdoc}
     * @return status.
     */

	public function Active($id, $state = -1)
    {
		if( $state < 0 ){
			$this->active = ($this->active == 1)?0:1;
		}else{
			$this->active = $state;
		}
		return $this->save();
	}

	public function search($search, $countList = 20)
    {
	 $sql = "SELECT SQL_CALC_FOUND_ROWS *, MATCH (`title`,`keywords`) AGAINST ('$search') AS rang FROM ".Story::tableName().
        " WHERE MATCH (`title`,`keywords`) AGAINST ('$search' IN BOOLEAN MODE) ".
        " AND active > 0 ".
        " ORDER BY rang DESC LIMIT ".$countList*1;
		return $this->findBySql($sql, [':search' => $search, ':limit' => $countList])->all();
	}

	public function getForNews($id)
    {
		$sql = 'select r.topic_id as id, title, t.active as active, url from '.StoryRelation::tableName().' r , '.Story::tableName().' t '.
				'where r.topic_id = t.id and r.news_id = '. $id.' order by `order`';
		return $this->findBySql($sql, [])->all();
	}

	/**
     * {@inheritdoc}
     * @return status.
     */
	public function saveImg($id, $file, $type)
    {
		$post = Yii::$app->request->post();
		$pcut = isset($post['cropping'])?$post['cropping']:false;
		$t = ['image/jpeg'=>'jpg','image/png'=>'png', 'image/webp'=>'webp']; //расширить допустимый список и вынести в общий класс
		if( isset( $t[$type] ) ){
			$ext = $t[$type];

			//загрузка временной фото на обработку
			$name = basename($id."_origin.".$ext);
			$file_tmp = Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";
			if( move_uploaded_file($file, $file_tmp) ){

				//			фото исходник для дальнейшей обработки
				$name = basename($id."_sizehd.jpg");
				$hdfile = Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";
				if( $pcut ){
					$cut = ['x'=>round($pcut['x']), 'y'=>round($pcut['y']), 'w'=>round($pcut['width']), 'h'=>round($pcut['height'])];
					$this->generateImageCrop($file_tmp, $hdfile, 1920, 1080, $cut);
				}else{
					// без обрезки
					$this->generatePreview( $file_tmp, $hdfile, 1920, 1080);
				}
				//unlink($file_tmp); удалить оригинал или оставить?

				//			фото на главную сюжета 1300х731
				$name = basename($id."_size1.webp");
				$ofile = Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";
				$this->generatePreview( $hdfile, $ofile, 1300, 731);
				$name = basename($id."_size1.jpg");
				$ofile = Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";
				$this->generatePreview( $hdfile, $ofile, 1300, 731);

				//			фото на в ленту(можно отдавать поисковикам) сюжета 680x383
				$name = basename($id."_size2.webp");
				$ofile = Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";
				$this->generatePreview( $file_tmp, $ofile, 680, 383);
				$name = basename($id."_size2.jpg");
				$ofile = Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";
				$this->generatePreview( $file_tmp, $ofile, 680, 383);

				// size3 пропустим в текущем дизайне не применим
				//			фото на в малая(можно отдавать в админку, инжекты и пр. лабудень) сюжета 320х180
				$name = basename($id."_size4.webp");
				$ofile = Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";
				$this->generatePreview( $file_tmp, $ofile, 320, 180 );
				$name = basename($id."_size4.jpg");
				$ofile = Yii::getAlias('@webroot').'/'.static::$story_dir."/$name";
				$this->generatePreview( $file_tmp, $ofile, 320, 180 );
				return true;
			}
		}
		return false;
    }

    public function getImage(){
        return new StoryImages(["topic_id"=>$this->id]);
    }
    public function behaviors()
    {
	  $keys = array_keys(self::$keysCache);
      return [
        'CachedBehavior' => [
          'class' => CachedBehavior::class,
          'cache_key' => $keys,
        ]
      ];
    }

}
