<?php
/**
 * Created by PhpStorm.
 * User: Jure
 * Date: 29.4.2014
 * Time: 17:31
 */
require_once '../AutoLoader.php';
$autoloader = new Autoloader();
ini_set("display_errors", "0");
define("absolute_path", "/var/www/html/warpitDevelopment/");

class NfieldControlManager
{
    public $surveyId;
    public $datetimeStart;
    public $datetimeEnd;

    function __construct($surveyId,$dateStart,$dateEnd)
    {
        $this->surveyId = $surveyId;
        $this->datetimeStart = $dateStart;
        $this->datetimeEnd = $dateEnd;
    }
    public function saveControlDataOnServerAction()
    {
        $backgroundTaskService = new NfieldBackgroundTasksService();
        $surveyDataService = new NfieldSurveyDataService();
        try {
            //Za testiranje
            //$surveyId = '8c58c100-47fd-4c35-8134-eedd5d5d2b04';
            //$backGroudId = '79c8f857-5400-40c1-9c72-b5e8ff8272ba';
            /*
             *  koncane ankete
                odprte odgovore
                zaprte odgovore
                paradata
                brez media
             */
            $surveyDataModel = new SurveyDownloadDataRequest();
            $surveyDataModel->setSurveyId($this->surveyId);
            $surveyDataModel->setDownloadCapturedMedia('false');
            $surveyDataModel->setDownloadClosedAnswerData('true');
            $surveyDataModel->setDownloadFileName('NameOfBackGroudsData');
            $surveyDataModel->setDownloadParaData('true');
            $surveyDataModel->setDownloadOpenAnswerData('true');
            $surveyDataModel->setDownloadSuccessfulLiveInterviewData('true');
            $surveyDataModel->setDownloadNotSuccessfulLiveInterviewData('true');
            $surveyDataModel->setDownloadTestInterviewData('true');
            $surveyDataModel->setStartDate($this->datetimeStart.'.13');
            //2014-05-02T08:49:49.13 format

            $surveyDataModel->setEndDate($this->datetimeEnd.'.13');

            $createdBackGround = $surveyDataService->post($surveyDataModel);
            //Wait for preparing download data
            //$createdBackGround = $backgroundTaskService->getDetailByProject($this->surveyId, $backGroudId);
            $createdBackGround = json_decode($createdBackGround, true);

            if (!isset($createdBackGround['Id'])) {
                return "{success:false,error:'Background task is null'}";
            }

            $backgroundModel = new BackgroundTask();
            $backgroundModel->setId($createdBackGround['Id']);

            $start_time = time();
            while(true) {
                if ((time() - $start_time) > 300) {
                    break; // timeout, function took longer than 300 seconds
                }
                $backgroundTask = $backgroundTaskService->getDetail($backgroundModel->getId());
                //$backgroundTask = $backgroundTaskService->getDetailByProject($this->surveyId, $backgroundModel->getId());
                $backgroundTask = json_decode($backgroundTask, true);
                if (isset($backgroundTask['ResultUrl'])) {
                    break;
                }
                sleep(5);
            }
            if (!isset($backgroundTask['ResultUrl'])) {
                return "{success:false,error:'Result url is not prepared'}";
            }

            $url = $backgroundTask['ResultUrl'];

            $targetLocation = absolute_path . 'nfield/docs';
            $fileName = '/tmp_file.zip';

            $savedFileLocation = $targetLocation . $fileName;
            $isFalse = file_put_contents($savedFileLocation, file_get_contents($url));
            if($isFalse === false){
                return "{success:false,error:'File put contents is failed'}";
            }

            $zip = new ZipArchive();
            if ($zip->open($savedFileLocation, ZipArchive::CREATE) == TRUE) {
                $zip->extractTo($targetLocation);
                $zip->close();
                echo "{success:true,message:'Download was successfully saved on server'}";
            } else {
                echo "{success:false,error:'Cannot open .zip file'}";
            }
        } catch (Exception $e) {
            echo "{success:false,error:'Http request is failed'}";
        }
    }

}

$comm = $_POST['action'].'Action';
//$comm = 'saveControlDataOnServerAction';
$nfieldId = $_POST['nfield_id'];
$datetimeStart = $_POST['startDatetime'];
$endDatetime = $_POST['endDatetime'];

$controlManager = new NfieldControlManager($nfieldId,$datetimeStart,$endDatetime);
if (method_exists($controlManager, $comm))
    echo $controlManager->$comm();
else {
    echo "{success:false,error:'Unknown action'}";
}

