<?php
namespace Steps;
use \Curl\Curl;

class CheckInternetConnection extends AbstractStep
{
  private $attempt = 0;

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

  public function execute()
  {
    $curl = new Curl();
    $curl->setTimeout(config('check_conection_timeout'));

  //  $curl->setHeader('Content-Type', 'application/json');
    $curl->setDefaultJsonDecoder();
    $curl->success([$this, "success"]);
    $curl->error([$this, "error"]);

    $curl->setOpt(CURLOPT_SSL_VERIFYHOST, config('ssl_verify'));
    $curl->setOpt(CURLOPT_SSL_VERIFYPEER, config('ssl_verify'));
    //$this->clientStatus->badInternetShow();
//    $curl->setConnectTimeout(5);
    $data = [];
    $data['action'] = 'start';
    $data['browser_data'] = $_SERVER['HTTP_USER_AGENT'];
    $data['client_id'] =  config('client-machine-id');
    $data['id_user'] = config('user_id');
    $data['start_version'] = $this->versions->getVersion();

    $curl->post(config('checkConnectionUrl'), $data);
  }

  public function success($curl)
  {
    if($curl->response)
    {
        $response = json_decode($curl->response, true);
        if($response['success'] && $response['id_log'])
        {
            $this->actionData->setLogId(intval($response['id_log']));
        }
        else
        {
            //TODO change this to more meaningfull error
            $this->clientStatus->noInternetConnection();
        }
    }
  }

  public function error($curl)
  {
      $this->attempt++;

      if($this->attempt < 2)
      {
          $this->clientStatus->badInternetShow();
          sleep(3);
          $this->execute();
      }
      else
      {
          $this->clientStatus->badInternetHide();
          $this->clientStatus->noInternetConnection();
      }
  }

}

 ?>
