<?php

namespace common\behaviors;

use common\modules\comment\models\CommentModel;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;
/**
 * Class RatingBehavior
 * @property CommentModel $owner
 * @package common\behaviors
 */
class SaveImgBehavior extends Behavior
{

    public $fields;
    //public $directory;

    public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
        ];
    }

    public function beforeUpdate($event)
    {
        foreach($this->fields as $field){
            if ( ($image = UploadedFile::getInstance($this->owner, $field['name'])) ) {
                $this->owner->{$field['name']} = $image->name;
            }

            if(!$this->owner->{$field['name']}){
                $this->owner->{$field['name']} = $this->owner->getOldAttribute($field['name']);
            }


            if ($image) {
                $imgDir = \Yii::getAlias('@storage/'.$field['directory'].'/');

                if(!is_dir($imgDir)) {
                    mkdir($imgDir, 0755, true);
                }

                $image->saveAs(\Yii::getAlias('@storage/'.$field['directory'].'/' . $image->name));
            }
        }



    }

    public function getImagesConfig($image = 'image') {
        $op = [];
        if ($this->owner->$image) {

                $op[] = [
                    'caption' => $this->owner->$image,
                    'url' => \yii\helpers\Url::to(['delimg', 'id' => $this->owner->primaryKey, 'field' =>$image ]),
                    'key' => $this->owner->primaryKey,
                    'extra' => [
                        'id' => $this->owner->primaryKey,
                    ],
                ];

        }
        return $op;
    }


    public function beforeInsert($event)
    {
        foreach($this->fields as $field){

            if ( ($image = UploadedFile::getInstance($this->owner, $field['name'])) ) {
                $this->owner->{$field['name']} = $image->name;
            }



            if ($image) {
                $imgDir = \Yii::getAlias('@storage/'.$field['directory'].'/');

                if(!is_dir($imgDir)) {
                    mkdir($imgDir, 0755, true);
                }

                $image->saveAs(\Yii::getAlias('@storage/'.$field['directory'].'/' . $image->name));
            }
        }
    }

    public function getImageFile($image = 'image') {
        return empty($this->owner->$image) ? null : '/storage/'.$this->fields[0]['directory'].'/'. $this->owner->$image;
    }

    public function getImageUrl($image = 'image') {
        return empty($this->owner->$image) ? null : '/storage/'.$this->fields[0]['directory'].'/'. $this->owner->$image;
    }



}