<?php
class Gallery {
	public function Index($params) {
		$albums=Album::GetAlbums();
		return new View("Gallery/index.view",array("albums"=>$albums));
	}
	
	public function View($params) {
		$album=new Album($params[0],true);
		Breadcrumbs::Add($album->AlbumTitle, "");
		return new View("Gallery/view.view",array("album"=>$album));
	}
	
	public function Manage($params) {
		$vars=array();
		Breadcrumbs::Add("Manage", "");
		$vars["albums"]=Album::GetAlbums(true,true);
		if (isset($params['errors']))
			$vars["errors"]=$params['errors'];
		$vars['images']=Image::GetImagesByAlbum(0);
		if(isset($params['image']))
			$vars['image']=$params['image'];
		else
			$vars['image']=new Image();
		return new View("Gallery/manage.view",$vars);
	}
	
	public function Move($params){
		if (!isset($params['moveImages']))
			return;
		//return print_r($params,true);
		foreach ($params['selected'] as $imgId){
			$image=new Image($imgId);
			$image->AlbumId=$params['selectAlbumNew'];
			$image->Save();
		}
		header("location:/gallery/manage");
	}
	
	public function CreateAlbum($params) {
		Breadcrumbs::Add("Manage", "");
		Breadcrumbs::Add("Create Album", "");
		$album=new Album();
		if (isset($params['title']))
			$album->AlbumTitle=$params['title'];
		if (isset($params['description']))
			$album->AlbumDescription=$params['description'];
		if ($album->AlbumTitle!="" && $album->AlbumDescription!=""){
			$album->Save();
			header("location:/gallery/manage");
			return;
		}
		return new View("Gallery/create_album.view",array("album"=>$album));
	}
	
	public function Upload($params) {
		if (!isset($_FILES['imageFile'])){
			header("location: /gallery/manage/");
			return;
		}
		$errors=array();
		$filename=$_FILES['imageFile']['name'];
		$tempFile=$_FILES['imageFile']['tmp_name'];
		if ($params['imageTitle']=="")
			$errors[]="The image doesn't have a title";
		if ($_FILES['imageFile']['error'])
			$errors[]=Utils::FileUploadErrorToMessage($_FILES['imageFile']['error']);
		if (count($errors)==0) {
			if(!Image::IsValidType(pathinfo($filename,PATHINFO_EXTENSION)))
				$errors[]="File is of an invalid type";
			if (getimagesize($tempFile)===false)
				$errors[]="File is not an image";
		}
		$image=new Image($filename,$tempFile);
		$image->ImageTitle=$params['imageTitle'];
		$image->ImageDescription=$params['imageDesc'];
		if (count($errors)==0){
			$image->Save();
			header("location: /gallery/manage/");
			return;
		}
		return $this->Manage(array("errors"=>$errors,"image"=>$image));
	}
	
	public function JsonLoadAlbum($params) {
		$json='[';
		$images=Image::GetImagesByAlbum($params[0]);
		foreach ($images as $image)
			$json.='{"ImageId":"'.$image->ImageId.'","ImageTitle":"'.$image->ImageTitle.'","Path":"'.$image->Path.'","ThumbnailPath":"'.$image->ThumbnailPath.'"},';
		$json=trim($json,',');
		$json.=']';
		return $json;
		//return json_encode($images);
	}
}
