<?php
namespace Steps;


class CopyFiles extends AbstractStep
{

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


  public function execute($data = null)
  {
      $this->clientStatus->copyingFiles();

      $fileType = \DataContainers\ActionData::FILETYPE_WEBPROJECTS;
      $webProjectsFiles = $this->actionData->getFiles($fileType);
      $this->copy($webProjectsFiles, $fileType);

      $fileType = \DataContainers\ActionData::FILETYPE_WARPIT;
      $warpitFiles = $this->actionData->getFiles($fileType);
      $this->copy($warpitFiles, $fileType);


  }

  private function copy($filesList, $fileType)
  {
    $version = $this->versions->current('version');
    $temporaryPath = config('localContainer').$version. '/' . config('temporaryFolderName')[$fileType];

    if(count($filesList))
    {
      $folder = $this->getFolder($fileType);
    //  var_dump($folder, $temporaryPath);
    //  var_dump(config('temporaryFolderName')[$fileType]);
      $succesCopy = array();
      foreach($filesList as $file)
      {
          $directory = $file[0] . '/';
          $path = $directory . $file[1];


          mkdir($folder . $directory, 0777, true);

          $from = $temporaryPath .'/' . $path;
          $to = $folder . $path;
          if(copy($from, $to))
          {
              $succesCopy[] = $path;
          }
          else
          {

              $data['folderType'] = $fileType;
              $data['error'] = error_get_last();
              $data['from'] = $from;
              $data['to'] = $to;
              $data['successCopy'] = $successCopy;
              $this->clientStatus->faildToCopyFiles($data);
          }
      }
      $data['folderType'] = $fileType;
      $data['files'] = $succesCopy;
      $this->clientStatus->filesCopied($data);
    }
  }

  public function getFolder($type)
  {
      if($type == \DataContainers\ActionData::FILETYPE_WARPIT) return WARPIT_ABSOLUTE;
      else return WARPIT_WEBPROJECTS;
  }

}
