<?php
/**
 * Created by PhpStorm.
 * User: PHOENIX
 * Date: 18.02.16
 * Time: 17:07
 */

namespace common\modules\triggers\components\conditions\conditions;


use common\modules\triggers\components\conditions\vendor\ConditionBase;
use common\modules\triggers\components\conditions\vendor\ConditionInterface;
use common\modules\triggers\models\TriggerCondition;
use common\modules\triggers\models\TriggerParam;
use common\modules\triggers\models\TriggerTrigger;

class CheckPresenceTime extends ConditionBase implements ConditionInterface {
    const CONDITION_ID=5;

    public $name = 'Время присутствия на странице';

    public $params=[];

    /**
     * @param null|string $conditionName
     * @return $this mixed
     */
    public static function init($conditionName=__CLASS__){
        return parent::init($conditionName);
    }

    public function initScript(){
        return true;
        /** @var TriggerTrigger[] $actualTriggers */
        $actualTriggers = TriggerTrigger::getActualTriggers(self::CONDITION_ID);
        foreach($actualTriggers as $trigger) {
            $conditions = TriggerCondition::find()->where(['trigger_id' => $trigger->getPrimaryKey()])->all();
            foreach($conditions as $condition) {
                /** @var TriggerParam $paramUrl */
                $paramUrl = TriggerParam::find()->where(['condition_id'=>$condition->getPrimaryKey(), 'key'=>'url'])->one();
                $paramTime = TriggerParam::find()->where(['condition_id'=>$condition->getPrimaryKey(), 'key'=>'time'])->one();
                if ($condition->condition_id==self::CONDITION_ID && $paramUrl!==null && $paramUrl->value==\Yii::$app->request->getUrl()) {
                    $view = \Yii::$app->controller->view;
                    $script ='$(window).on("beforeunload", function() {
                                    var timer='.(($paramTime!==null) ? $paramTime->value : 0).';
                                    if(timer>0){
                                        $.ajax({
                                            url: "/triggers/default/inittrigger",
                                            method: "GET",
                                            async: false,
                                            data: {
                                                id: '.$trigger->getPrimaryKey().'
                                            },
                                        });
                                    }
                               });';
                    echo $view->registerJs($script, $view::POS_READY);
                }
            }
        }
    }

    /**
     * @param $time
     * @return bool
     */
    public function check($time){
        return true;
    }
} 