<?php

class DownloadJob extends Job {

	public $from = null;
	public $to = null;
	public $revid = null;

	private $_pct = 0;

	public function __construct($revid, $from, $to) {
		$this->from = $from;
		$this->to = $to;
		$this->revid = $revid;
		parent::__construct("revision:" . $revid);
	}
	
	public function run() {
		$ch = curl_init();
		$this->status("Downloading: 0%");
		$fd = fopen($this->to, "w");

		print_r($this);

		curl_setopt($ch, CURLOPT_URL, $this->from);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36");
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
		curl_setopt($ch, CURLOPT_PRIVATE, $this);
		curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
        curl_setopt($ch, CURLOPT_FILETIME, true);
		curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, [$this, 'download_progress']);
		curl_setopt($ch, CURLOPT_NOPROGRESS, false);
		curl_setopt($ch, CURLOPT_FILE, $fd);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

		print("Running...\n");
		$r = curl_exec($ch);
		fclose($fd);
		$sha = hash_file("sha256", $this->to);
		$rev = new Revision($this->revid);
		$rev->sha256 = $sha;
		$rev->save();
		print("Finished\n");
	}



	function download_progress($ch, $download_size, $downloaded, $upload_size, $uploaded) {
		if ($download_size == 0) return;
		$pct = round($downloaded / $download_size * 100);
		if ($pct != $this->_pct) {
			$this->status("Downloading: " . $pct . "%");
			$this->_pct = $pct;
		}
	}
}
