<?php

require_once(__DIR__ . "/File.php");

class Image extends File {
	private $_img = null;
	private $_type = null;

	public function __construct($w, $h = null) {

		if ($w instanceof File) {
			$w = $w->path();
		}

		if ($h === null) {
			parent::__construct($w);
			$this->_type = $this->mime();
		} else {
			$this->_img = ImageCreateTrueColor($w, $h);
		}

	}

	public function getImage() {
		if ($this->_img == null) {
			if ($this->_type === false) {
				$this->_img = ImageCreateTrueColor(1, 1);
			} else {
				switch ($this->_type) {
					case "image/png":
						$this->_img = ImageCreateFromPNG($this->path());
						break;
					case "image/jpeg":
						$this->_img = ImageCreateFromJPEG($this->path());
						break;
					case "image/gif":
						$this->_img = ImageCreateFromGIF($this->path());
						break;
				}
			}
		}
		return $this->_img;
	}

	public function save($fn = null, $type = null) {
		$newimg = true;
		if ($fn == null) {
			$fn = $this->path();
			$newimg = false;
		}
		if ($type == null) {
			$type = $this->_type;
			$newimg = false;
		}

		switch ($type) {
			case "image/png":
				ImagePNG($this->getImage(), $fn);
				break;
			case "image/jpeg":
				ImageJPEG($this->getImage(), $fn);
				break;
			case "image/gif":
				ImageGIF($this->getImage(), $fn);
				break;
			default:
				throw new Exception("Invalid mime type $type specified");
		}
		if ($newimg) {
			return new Image($fn);
		}
		return $this;
	}

	public function width() {
		return ImageSX($this->getImage());
	}

	public function height() {
		return ImageSY($this->getImage());
	}

	public function scale($w, $h = 0) {

		$sx = $this->width();
		$sy = $this->height();
		$dx = $w;

		if ($h == 0) {
			$aspect = $sx / $sy;
			$dy = (int)($dx / $aspect);
		} else {
			$dh = $h;
		}

		$new = ImageCreateTrueColor($dx, $dy);
		ImageCopyResampled($new, $this->getImage(), 0, 0, 0, 0, (int)$dx, (int)$dy, (int)$sx, (int)$sy);
		ImageDestroy($this->getImage());

		$this->_img = $new;
			
	}

	public function emit() {
		$this->set_header("Content-Type", $this->_type);
		$this->set_header("Cache-Control", "public, max-age=86400, must-revalidate");
		$this->set_header("Content-Disposition", "inline; filename=" . $this->basename());

		parent::emit();
	}

	public function color($r, $g, $b) {
		return ImageColorAllocate($this->getImage(), $r, $g, $b);
	}

	public function clear($c) {
		ImageFilledRectangle($this->getImage(), 0, 0, $this->width(), $this->height(), $c);
	}

	public function text($x, $y, $t, $c, $f) {
		ImageString($this->getImage(), $f, $x, $y, $t, $c);
	}

}
