<?php

namespace Steps;
use \Curl\Curl;

class DownloadVersions extends AbstractStep
{
    private $versionsToDownload = array();

    public function execute()
    {
        if(!$this->versions->isLoaded())
        {
            $this->clientStatus->downloadProcessStarted();
            $this->downloadVersions();
        }
    }

    public function downloadVersions()
    {

        $url =            config('versionControlUrl');
        $clientID =       config('client-machine-id');
        $id_user =        config('user_id');
        $clientVersion =  $this->versions->getVersion();

        $data = array("client_version" => $clientVersion, "client-machine-id" => $clientID, "user_id" => $id_user);

        $curl = new Curl();

        $curl->setDefaultDecoder("xml");
        $curl->success([$this, "success"]);
        $curl->error([$this, "error"]);

        $curl->setOpt(CURLOPT_SSL_VERIFYHOST, config('ssl_verify'));
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, config('ssl_verify'));

        $curl->get($url, $data);
    }

    public function success($curl)
    {
      if($curl->response)
      {
        foreach ($curl->response->version as $ver)
        {
            $this->versionsToDownload[] = array(
            "version" => (string)$ver->file_program_ver,
            "checksum" =>(string) $ver->checksum,
            "major_version" => (string) $ver->major_version
          );
        }
      }

      if(count($this->versionsToDownload) > 0)
        $this->versions->setVersions($this->versionsToDownload);

      $reportData = array();
      $reportData['curlRepsonse'] = $curl->response;
      $reportData['versionsToDownload'] = $this->versionsToDownload;

      $this->clientStatus->versionsDownloaded($reportData);
    }

    public function error($curl)
    {
        if($curl->error)
        {
            $reportData['curlErrorCode'] = $curl->errorCode;
            $reportData['curlErrorMessage'] = $curl->errorMessage;
            $reportData['url'] = $curl->url;

            $this->clientStatus->versionsDownloadError($reportData);
        }
    }

    public function response()
    {
        return;
    }
}
