<?php
  class ControllerCommonTask extends Controller {

    public function index() {


      $this->load->dmodel('setting/task');
      $this->load->type('tipocomum');

      ini_set('max_execution_time', Type_ExecTimeTask::Tp_ExecTime_5min);

      $tasks     = array();

      $data      = new DateTime($this->db->dataAtual(), new DateTimeZone('America/Sao_Paulo'));
      $dataAtual = $data->format("Y-m-d H:i:s");

      $results = $this->dmodel_setting_task->getTasks();
      foreach ($results as $key => $result) {

        if($this->getTaskEnabled(Type_TaskConfigStatus::getNickFromConstValue($key))){
          $dominio       = ($key == Type_TaskUrl::Tp_TaskShopLineSonda) ? true : false ;

          $result['predefined_execution'] = is_null($result['predefined_execution']) ? Type_PreConfigTask::Tp_PreConfigTask_Manual : $result['predefined_execution'];

          switch ($result['predefined_execution']){
            case Type_PreConfigTask::Tp_PreConfigTask_Manual:
              if(!is_null($result['date_last_acting'])){
                $dateExecution   = date_format(date_add(date_create($result['date_last_acting']), new DateInterval("PT0H".$result['time_execution']."M0S")), 'Y-m-d H:i:s') ;
                
                $data->modify('+1 minute'); /* Adiciona um min a data atual para que as tasks não deixem de rodar devido aos segundos  */
                $dataAtual = $data->format("Y-m-d H:i:s");

                if($dataAtual > $dateExecution){
                  $tasks = array_merge($tasks, array($this->url->link(Type_TaskUrl::getNickFromValue($result['type']), '', 'SSL', !$dominio, $dominio)));
                }
              }else{
                  $tasks = array_merge($tasks, array($this->url->link(Type_TaskUrl::getNickFromValue($result['type']), '', 'SSL', !$dominio, $dominio)));
              }
            break;
            case Type_PreConfigTask::Tp_PreConfigTask_1AM:
            case Type_PreConfigTask::TP_PreConfigTask_3AM:
              $timeExec      = new DateTime( Type_PreConfigTask::getNickFromConstValue($result['predefined_execution']), new DateTimeZone('America/Sao_Paulo'));
              if (!is_null($result['date_last_acting'])){
                $dateExecution =  date_format(date_create($result['date_last_acting']),'Y-m-d') < $data->format("Y-m-d");//não rodar 2x no mesmo dia
              }else{
                $dateExecution = true;
              }

              if (($data->format("H") == $timeExec->format("H"))  && ($dateExecution) ){
                $tasks = array_merge($tasks, array($this->url->link(Type_TaskUrl::getNickFromValue($result['type']), '', 'SSL', !$dominio, $dominio)));
              };
            break;
          }

        }

      }

      $url_count = count($tasks);

      $curl_array = array();
      $ch = curl_multi_init();

      foreach($tasks as $count => $url) {
        $curl_array[$count] = curl_init($url);
        curl_setopt($curl_array[$count], CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_array[$count], CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl_array[$count], CURLOPT_SSL_VERIFYHOST, 0);
        curl_multi_add_handle($ch, $curl_array[$count]);
      }

      $count = 1;
      do {
        if($count >= 60){//5 segundos de sleep * 50 = 4 minutos, caso chegar nesse tempo, corta o processo...
          break;
        }
        curl_multi_exec($ch, $exec);
        usleep(5000000);
        $count ++;
      } while($exec > 0);

      foreach($tasks as $count => $url) {
        $returned = curl_multi_getcontent($curl_array[$count]);
      }

      foreach($tasks as $count => $url) {
        curl_multi_remove_handle($ch, $curl_array[$count]);
      }

      curl_multi_close($ch);

      foreach($tasks as $count => $url) {
          curl_close($curl_array[$count]);
      }

    }

    private function getTaskEnabled ($conditions){
        if (is_bool($conditions)){
            // Se for boolean retorna o mesmo
            return $conditions;

        } else if (strpos($conditions,'|') !== false) {
            // Se tiver pipe depende de varias configs
            $configKeys = explode('|', $conditions);
            foreach ($configKeys as $configKey) {
                if ($this->config->get($configKey)){
                    return true;
                }
            }

        } else {
            // Senao e uma unica config
            return $this->config->get($conditions);
        }

        return false;
    }

  }
?>
