<?php

//TODO catch some server errors

namespace Steps;

use \Curl\Curl;

class DownloadZip extends AbstractStep
{
    private $prev = 0;

    private $counter = 0;

    private $prevDownload = 0;

    private $alreadyDownloaded = 0;

    private $badInternetWarning = 0;

//    private $numberOfAttempts = 0;

    private $fileSize = 0;

    public function execute()
    {
      $this->counter = 0;
      $this->prevDownload = 0;

      $version = $this->versions->current('version');
      $fileName = "version_" . $version . ".zip";

      $remotePath =  config('remoteContainer') . $fileName;
      $localPath =  config('localContainer');

      if(!file_exists($localPath)) $this->clientStatus->temporaryFolderFail($localPath);

      $localPath .= $fileName;


      $curl = new Curl();
      $curl->setTimeout(intval(config('connection_timeout')));
      $curl->setOpt(CURLOPT_BUFFERSIZE, 128000);
  //    $curl->setConnectTimeout(5);

      $curl->progress([$this, "progressFunction"]);
      $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->zipFileDownloadStarted(array('version' => $version));

    /*  $md5 = null;
      $expectedMD5 = null;
      if(file_exists($localPath))
      {
        /*  $this->alreadyDownloaded = filesize($localPath);
          $curl->setRange($this->alreadyDownloaded);

        /*  $md5 = md5_file($localPath);
          $expectedMD5 = $this->versions->current('checksum');

          //We already downloaded file
          if($md5 == $expectedMD5)
          {
              $this->clientStatus->zipFileDownloadSucces(array('localPath' => $localPath));
              $this->clientStatus->updateProgressbar(array('percent' => 100, 'version' => $version));
              return;
          }
      }*/
      if($this->continueDownload($localPath, $remotePath))
      {
        $curl->setRange($this->alreadyDownloaded);
        $this->clientStatus->updateProgressbar(array('percent' => 0, 'version' => $version));
        $curl->download($remotePath, $localPath);
      }

      //TODO check if file id partli downloaded ect

    }

    public function success($curl)
    {
        $this->clientStatus->updateProgressbar(array('percent' => 100, 'version' => $version));

        $version = $this->versions->current('version');
        $fileName = "version_" . $version . ".zip";

        $localPath =  config('localContainer'). $fileName;

        $expectedMD5 = $this->versions->current('checksum');
        $actualMD5 = md5_file($localPath);
        $file_exists = file_exists($localPath);

        if($file_exists && $expectedMD5 == $actualMD5)
        {
            $data['localPath'] = $localPath;
            $this->clientStatus->zipFileDownloadSucces($data);
        }
        else
        {
            unlink($localPath);
            $data['expectedChecksum'] = $expectedMD5;
            $data['actualMD5'] = $actualMD5;
            $data['file_exists'] = $file_exists;
            $data['localPath'] = $localPath;

            $this->clientStatus->wrongChecksum($data);
        }

        $this->alreadyDownloaded = 0;
    }

    public function error($curl)
    {
      /*  if($curl->error && $curl->errorCode == 28)
        {
              if($this->numberOfAttempts < 2)
              {
                  $this->execute();
                  $this->numberOfAttempts++;
              }
        }*/

      //  $this->saveFileSize($localPath, $curl->responseHeaders['content-length']);
        $this->clientStatus->downloadZipFaild($curl);

    }

    private function getFilesize($path)
    {
        if($this->fileSize == 0)
        {
          $curl = new Curl();
          $curl->setTimeout(3);

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

          $curl->head($path);

          $this->filesize = $curl->responseHeaders->offsetGet('content-length');
        }

        return $this->filesize;
    }

    private function continueDownload($localPath, $remotePath)
    {
        if(!file_exists($localPath)) return true;

        $this->alreadyDownloaded = filesize($localPath);

        if($this->getFilesize($remotePath) > $this->alreadyDownloaded)
            return true;
        else
        {
          $this->success(null);
          return false;
        }


    }

    public function progressFunction($client, $download_size, $downloaded, $upload_size, $uploaded)
    {

        if($download_size <= 0) return;
		//print "progresss";
        $version = $this->versions->current('version');
        if($this->alreadyDownloaded > 0)
        {
            $downloaded+=$this->alreadyDownloaded;
            $download_size+=$this->alreadyDownloaded;
        }

        $percent = floor( $downloaded * 100 / $download_size );



        if($this->prev < $percent || $percent == 100)
        {
          $this->clientStatus->updateProgressbar(array('percent' => $percent, 'version' => $version ));

          $this->prev = $percent + 5;
        }

      /*  if($this->prevDownload >= $downloaded)
        {
            $this->counter++;
        }
        else if($this->badInternetWarning)
        {
            $this->counter = 0;
            $this->clientStatus->badInternetHide(array('version' => $version));
            $this->badInternetWarning = 0;
        }

        if($this->counter > 15 && !$this->badInternetWarning)
        {
            $this->clientStatus->badInternetShow(array('version' => $version));
            $this->badInternetWarning = 1;
            $this->counter = 0;
        }

        $this->prevDownload = $downloaded;*/
    }
}
