<?php

namespace app\models\procedure;

use Yii;
use yii\base\Model;
//use app\models\entity\Accounts;
//use app\models\entity\Projecttypes;
//use app\models\entity\ProjectsLocotech;
use app\models\entity\Tasks;
use app\models\entity\Checkpoints;

/*

measurement_add: BEGIN

	declare tmp integer;

    select id into tmp
		from tasks t
        where id = task_id;
	if tmp is null then leave measurement_add; end if;

	#Добавляем чекпойнт для ручного замера.
	
    insert into checkpoints
		(type, text, parent_task_id, parent_checkpoint_id, is_set, measurement_field, measurement_id)
        values
        (819, measure_text, task_id, 0, 0, 'measurement_value', measure_id);

	
END

*/


class AsusgAddMeasurementToTaskModel extends Model 
{   

    private $measure_text;
    private $measure_id;
    private $task_id;
    private $initiator;
    private $extra;
    private $typesCheckpointsArray;
    private $typesCheckpoint;

    public function execute($task_id, $measure_id, $measure_text, $extra = false )
    {
        //$this->initiator = $initiator;
        $this->task_id = $task_id;
        $this->measure_id = $measure_id;
        $this->measure_text = $measure_text;
        $this->extra = $extra;
        $this->typesCheckpointsArray = [293,294]; // это типы чекпоинтов ( да, нет )
        $this->typesCheckpoint = 819;
        
        #Проверка на существование таска.
        if( !$this->isTask() ) {
            return false;
        }
        
        if ( !$extra ) {
            #Добавляем чекпойнт для ручного замера.
            if( !$this->addCheckpoint() ) {
                return false;
            }
        } else {
            foreach ( $this->typesCheckpointsArray as $type) {
                $this->typesCheckpoint = $type;
                $this->addCheckpoint();
            }
        }
        
    }
    
    #Проверка на существование таска.
    private function isTask() 
    {
        $result = false;
        $tasksEntity = Tasks::findOne($this->task_id);
        
        if( null !== $tasksEntity) {
            $result = true;
        }
        return $result;
    }
    
    #Добавляем чекпойнт для ручного замера.
    
    private function addCheckpoint()
    {
    
        $checkpointsEntity = new Checkpoints();
        $checkpointsEntity->type                 = $this->typesCheckpoint;
        $checkpointsEntity->text                 = $this->measure_text;
        $checkpointsEntity->parent_task_id       = $this->task_id;
        $checkpointsEntity->parent_checkpoint_id = 0;
        $checkpointsEntity->is_set               = 0;
        $checkpointsEntity->measurement_field    = 'measurement_value';
        $checkpointsEntity->measurement_id       = $this->measure_id;
        $checkpointsEntity->save();
        return true;
    }
}