<?php


class Video
{
	const NOT_CONTROLLED = 0;
	const REJECTED = -1;
	const ACCEPTED = 1;

	private $id;
	private $team;
	private $problem;
	private $link;
	private $reason;
	private $validation;
	private $uploaded_at;
	private $year;
	private $version;

	private function __construct() {}

	public static function fromId($id)
	{
		global $DB;
		$req = $DB->prepare("SELECT * FROM `videos` WHERE `id` = ?;");
		$req->execute([htmlspecialchars($id)]);
		$data = $req->fetch();

		if ($data === false)
			return null;

		$video = new Video();
		$video->fill($data);
		return $video;
	}

	public static function getVideos($reason, $problem, $validation_min = -1, $team_id = -1)
	{
		global $DB, $YEAR;
		$req = $DB->query("SELECT * FROM `videos` AS `t1` "
			. "INNER JOIN (SELECT `team`, `problem`, `reason`, MAX(`uploaded_at`) AS `last_upload`, COUNT(`team`) AS `version` FROM `videos` "
			. "WHERE `validation` >= $validation_min AND `year` = $YEAR GROUP BY `problem`, `reason`, `team`) `t2` "
			. "ON `t1`.`team` = `t2`.`team` AND `t1`.`reason` = `t2`.`reason` AND `t1`.`problem` = `t2`.`problem` "
			. "WHERE `t1`.`uploaded_at` = `t2`.`last_upload` AND `t1`.`problem` = $problem AND `t1`.`reason` = '" . Reason::getName($reason) . "'"
			. ($team_id >= 0 ? " AND `t1`.`team` = $team_id" : "")
			. " AND `validation` >= $validation_min AND `year` = $YEAR ORDER BY `t1`.`problem`, `t1`.`reason`;");

		$videos = [];

		while (($data = $req->fetch()) !== false) {
			$video = new Video();
			$video->fill($data);
			$videos[] = $video;
		}

		return $videos;
	}

	/**
	 * @param int $reason
	 * @param Team $team
	 * @param int $validation_min
	 * @return Video|null
	 */
	public static function getVideo($reason, Team $team, $validation_min = -1) {
		$videos = self::getVideos($reason, $team->getProblem(), $validation_min, $team->getId());
		if (sizeof($videos) == 0)
			return null;
		else
			return $videos[0];
	}

	private function fill($data)
	{
		foreach ($data as $key => $value)
			$this->$key = $value;

		$this->reason = Reason::fromName($this->reason);
	}

	public function getId()
	{
		return $this->id;
	}

	public function getTeam()
	{
		return $this->team;
	}

	public function getProblem()
	{
		return $this->problem;
	}

	public function getLink()
	{
		return $this->link;
	}

	public function getReason()
	{
		return $this->reason;
	}

	public function getValidation()
	{
		return $this->validation;
	}

	public function setValidation($validation)
	{
		global $DB;
		$this->validation = $validation;
		$DB->exec("UPDATE `videos` SET `validation` = $validation WHERE `id` = $this->id;");
	}

	public function getUploadedAt()
	{
		return $this->uploaded_at;
	}

	public function getYear()
	{
		return $this->year;
	}

	public function getVersion()
	{
		return $this->version;
	}
}