<?php
namespace Steps;

use \ActionData;
use \db;

class ExecuteScript extends AbstractStep
{

  public function __construct(\DataContainers\ActionData $actionData, db $db)
  {
      $this->actionData = $actionData;
      $this->db = $db;
  }


  public function execute($data = null)
  {
    //TODO naštej fielde
    $sql = "SELECT * FROM " . DB_WARPIT_LIVEUPDATE . "._LiveUpdateScripts WHERE active = 1";
    $res = $this->db->SQLexecute($sql);

    $executed = array();

    while ($zad = $this->db->fetchAssoc($res))
    {
        $scriptPath =  $zad['script_path'];
        $scriptId = $zad['id'];

        $path = WARPIT_WEBPROJECTS .$scriptPath;
        $exstension = pathinfo($path, PATHINFO_EXTENSION);

        $executed = array();
        if(strlen($scriptPath) < 5)
          $this->clientStatus->scriptNotValid();

        else if($exstension != "php")
          $this->clientStatus->scriptWrongExstension();

        else if(!file_exists($path))
          $this->clientStatus->scriptNotFound();

        else
        {
          //TODO better error catching
            try
            {
              $scriptParams = json_decode($zad["paramsJSON"]);
              include($path);
              $this->clientStatus->addExcutedScript(array('scriptPath' => $path, 'output' => \DisplayOutput::getFromBuffer()));
          //    $this->markAsExecuted($zad['id']);
            //  $status = ScriptStatus::EXECUTION_SUCCESSFULL;

              $executed[] = $scriptId;
            }
            catch (Exception $e)
            {
              $this->clientStatus->faildToExecuteScript($e);
              //  $status = ScriptStatus::EXECUTION_FAILD;
            }

            $this->markAsExecuted($executed);
        }
      //  $clientUpdate->addScript($path, $status);

    }
  }

  public function markAsExecuted($scriptIds)
  {
      $sql = "UPDATE " . DB_WARPIT_LIVEUPDATE . "._LiveUpdateScripts SET active = 0 WHERE id IN(" . implode(',', $scriptIds) . ") ";
      $this->db->SQLexecute($sql);
  }
}
