<?php

namespace app\models\base;

use yii\db\ActiveRecord;
use yii\helpers\Url;
use app\models\Person;
use app\models\base\Tags;
use app\models\base\Story;
use app\models\base\NewsTopic;

class BaseFrontendClass extends ActiveRecord
{
    public static function getDb()
    {
        return \Yii::$app->db;
    }

    public function getUrl($full = false):string
    {
        $base = Url::base('https');
        $page = \Yii::$app->request->get('page');
		$addpage = $page?'?page='.$page:'';
        if( $this instanceof NewsTopic || $this instanceof Story || $this instanceof Tags ){
			$alias = trim( $this->url );
		}else if($this instanceof News){
			$alias = trim( $this->alias );
			return ($full ? $base : "")."/news/".$alias."-".$this->id;
		}else if( $this instanceof Person ){
			$alias = trim( $this->alias );
			 return ($full ? $base : "")."/person/".$alias;
		}else{
			return false;
		}
		if( $this instanceof Tags) return ($full ? $base : "")."/tags/".$alias.$addpage;
		return ($full ? $base : "")."/news/".$alias.$addpage;
    }

    public function generatePreview( $ifile, $ofile, $w, $h, $param = array())
    {
		extract( $param );

		$addp = '';
		if( strrpos($ofile, '.webp') == strlen($ofile) - strlen('.webp') )
		{
			$addp = " -background '#FFFFFF' -alpha off -strip Plane -quality 88 -define webp:method=6 "; //-interlace
		}else{
			$addp = " -quality 95";
		}
		if(isset($sharpen))
		{
			$addp = $addp." -sharpen ".$sharpen;
		}
		list($width, $height) = getimagesize($ifile);
//		echo "convert -define jpeg:size=".$w."x".$h."+".$x."+".$y." $ifile -crop ".$w."x".$h."+".$x."+".$y." -thumbnail ".$ww."x".$hh."^ -gravity center $ofile";
		umask(0113);
		exec("convert -define jpeg:size=".$width."x".$height."+0+0 $ifile -thumbnail ".$w."x".$h."^ -gravity center -background '#FFFFFF' $addp $ofile" );
		@chmod($ofile, 0664);
    }

    public function generateImageCrop( $ifile, $ofile, $ww, $hh, $param )
    {
		// to do add rotate, etc
		extract( $param );
		list($width, $height) = getimagesize($ifile);
		$addp = '';
		if( strrpos($ofile, '.webp') == strlen($ofile) - strlen('.webp') )
		{
			$addp = " -background '#FFFFFF' -alpha off -strip Plane -quality 88 -define webp:method=6 "; //-interlace
		}
		if(isset($sharpen))
		{
			$addp = $addp." -sharpen ".$sharpen;
		}
		umask(0113);
//		echo "convert -define jpeg:size=".$w."x".$h."+".$x."+".$y." $ifile -crop ".$w."x".$h."+".$x."+".$y." -thumbnail ".$ww."x".$hh."^ -gravity center $ofile";
		exec("convert -define jpeg:size=".$width."x".$height."+0+0 $ifile -crop ".$w."x".$h."+".$x."+".$y." -thumbnail ".$ww."x".$hh."^ $addp -gravity center $ofile" ); //> /dev/null 2>&1 & > /dev/null & в фоне
//		chmod($ofile, 0664);
    }
	/**
     * {@inheritdoc}
     * @return status
     */
    public function clearNewsSTG($id)
    {
		$status = $this->db->createCommand()->delete(self::tableName(), [
				'news_id' => $id
		])->execute();
        return $status;
    }

}
