<?php

namespace common\models;

use common\modules\blog\models\Article;
use common\modules\blog\models\ArticleCategoryMedia;
use common\modules\blog\models\ArticleMedia;
use Yii;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;

/**
 * This is the model class for table "media".
 *
 * @property integer $media_id
 * @property string $hash
 * @property string $extension
 *
 * @property ArticleCategoryMedia[] $articleCategoryMedia
 * @property ArticleMedia[] $articleMedia
 */
class Media extends ActiveRecord
{
    /**
     * @var UploadedFile[];
     */
    public $imageFile;

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['media_id'], 'integer'],
            [['hash', 'extension'], 'string'],
            [['imageFile'], 'file', 'extensions' => 'png, gif, jpeg, jpg', 'skipOnEmpty' => true],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'media_id' => Yii::t('app', 'ID'),
            'hash' => Yii::t('app', 'Hash'),
            'extension' => Yii::t('app', 'Extension'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getArticleCategoryMedia()
    {
        return $this->hasMany(ArticleCategoryMedia::className(), ['media_id' => 'media_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getArticleMedia()
    {
        return $this->hasMany(ArticleMedia::className(), ['media_id' => 'media_id']);
    }

    public function getArticle()
    {
        return $this->hasMany(Article::className(), ['article_id' => 'article_id'])->via('articleMedia');
    }

    public function upload()
    {
        if(!empty($this->imageFile) && $this->validate('imageFile'))
        {
            $uploaddir = \Yii::getAlias('@saveImageDir');
            $this->hash = md5_file($this->imageFile->tempName).\Yii::$app->security->generateRandomString(5);
            $this->extension = $this->imageFile->extension;
            if(is_dir($uploaddir.$this->hash)) {
                return false;
            } else {
                if(!mkdir($uploaddir.$this->hash, 0755)) {
                    return false;
                }
            }
            $this->imageFile->saveAs($uploaddir.$this->hash.'/original.'.$this->imageFile->extension, false);
            if($this->save(false)) {
                return true;
            } else {
                $this->addError('imageFile', \Yii::t('app', 'Cannot load file'));
                return false;
            }
        } else {
            return false;
        }
    }

    public function delete()
    {
        $uploaddir = \Yii::getAlias('@saveImageDir');
        if(is_dir($uploaddir.$this->hash)) {
            $this->removeDir($uploaddir.$this->hash);
        }
        return parent::delete();
    }

    public function removeDir($dir)
    {
        if($objs = glob($dir."/*")) {
            foreach($objs as $obj) {
                is_dir($obj) ? removeDir($obj) : unlink($obj);
            }
        }
        rmdir($dir);
    }
}
