<?php
/**
 * class image
 *
 * Description for class image
 *
 * @author:
*/
namespace core;

class image {
	private $object = null;
	private $filePath = "";
	private $mimeType = "";
	private $width = 0;
	private $height = 0;

	public function __construct($filePath) {
		if(!file_exists($filePath)) {
			print "Plik {$filePath} nie istnieje!";
			exit;
		}
		
		$this->filePath = $filePath;
		
		$fileInfo = getimagesize($this->filePath);
		list($width, $height, $constant, $imgHTML) = $fileInfo;
		$this->mimeType = $fileInfo["mime"];

		switch($this->mimeType) {
			case "image/png":
				$this->object = imagecreatefrompng($this->filePath);
				break;
			default:
				print "Typ pliku {$mimeType} nie jest jeszcze obsłużony!";
				exit;
		}

		$this->width = $width;
		$this->height = $height;
	}

	public function setBackground($red, $green, $blue) {
		$background = imagecreatetruecolor($this->width, $this->height);
		imagefill($background, 0, 0, imagecolorallocate($background, $red, $green, $blue));
		imagecopy($background, $this->object, 0, 0, 0, 0, $this->width, $this->height);

		$this->object = $background;
	}

	public function setBackgroundHEX($hexString) {
		$hexString = "#".ltrim($hexString, "#");
		
		list($red, $green, $blue) = sscanf($hexString, "#%02x%02x%02x");
		
		self::setBackground($red, $green, $blue);
	}

	public function scale($width, $height) {
		
	}

	public function crop($width, $height) {
		
	}

	public function save($filePath, $qualityPercent = 100) {
		$success = false;

		switch($this->mimeType) {
			case "image/png":
				$qualityPNG = 100 - $qualityPercent;
				if($qualityPNG > 0) {
					$qualityPNG = round($qualityPNG / 100 * 9);
				}
				
				$success = imagepng($this->object, $filePath, $qualityPNG);
				break;
		}

		return $success;
	}
}
?>