<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/



class lc_album_image
{
	function __construct($image_id=null)
	{
		if ($image_id)
		{
			if ($info=$this->getImageInfo($image_id))
			{
				foreach($info as $key=>$item)
				{
					$this->$key=$item;
				}
			}
			
		}
	}

	public function getImageInfo($image_id)
	{
		$image=Db::i()->selectRow("SELECT image_id as id, album_id, name, `describe`, filename, `sort` FROM ?_lc_album_images WHERE image_id=?", $image_id);
		if (!$image) return false;
		$image['describe_html']=getbb($image['describe']);
		$image=self::setImagePath($image);
		return $image;
	}
	
	public static function addImage($data, $album_id)
	{
		if ($info=self::_uploadImage($data['Filedata']))
		{
			$info['image_id']=Db::i()->query("INSERT INTO ?_lc_album_images (album_id, name, `describe`, filename) VALUES(?, ?, ?, ?)", $album_id, $data['name'], $data['describe'], $info['name']);
			Db::i()->query("UPDATE ?_lc_album_images SET sort=image_id WHERE image_id=?", $info['image_id']);
			return $info;
		}
	}
	
	public function editImage($data)
	{
		if ($data['Filedata']['tmp_name'])
		{
			$fileinfo=self::_uploadImage($data['Filedata']);
			if ($fileinfo && $fileinfo['name']!=$this->filename) self::deleteFiles($this->filename);
		}
		Db::i()->query("UPDATE ?_lc_album_images SET {filename=?,} name=?, `describe`=?, album_id=? WHERE image_id=?", $fileinfo?$fileinfo['name']:DBSIMPLE_SKIP, $data['name'], $data['describe'], $data['album_id'], $this->id);
		if ($this->album_id!=$data['album_id']) Db::i()->query("UPDATE f_lc_album_images SET `sort`=(SELECT `sort` FROM (SELECT MAX(sort)+1 as `sort` FROM f_lc_album_images WHERE album_id=?) as m) WHERE image_id=?", $data['album_id'], $this->id);
		return $data['save']?'save':'next';
	}
	
	public function deleteImage()
	{
		Db::i()->query("DELETE FROM ?_lc_album_images WHERE image_id=?", $this->id);
		self::deleteFiles($this->filename);
	}
	
	public static function deleteFiles($filename)
	{
		foreach(lc_album_main::$tn as $tn)
		{
			unlink(LAB_PATH_ROOT.lc_album_main::$basepath.$tn['path'].'/'.$filename);
		}
	}
	
	protected static function _uploadImage($file)
	{
		foreach(lc_album_main::$tn as $tn)
			if (!is_dir(LAB_PATH_ROOT.lc_album_main::$basepath.$tn['path'])) mkdir(LAB_PATH_ROOT.lc_album_main::$basepath.$tn['path'], 0777, true);
			
		$img_info=getimagesize($file['tmp_name']);
		if (!($img_info[2]>0 && $img_info[2]<4)) return LabCMS::i()->error("Недопустимый формат файла");
		
		$name=preg_replace('/\.[^.]+$/','', $file['name']);
		if (lc_album_main::$tn['original']['type']) $ext=lc_album_main::$tn['original']['type'];
		else $ext=image_type_to_extension($img_info[2], false);
		$name=self::_prepareFilename($name, $ext);
		
		foreach (lc_album_main::$tn as $key=>$tn)
		{
			$folder=$tn['path'];
			$img=new Image_Resize();
			if ($tn['type'])
			{
				$ext=$img->new_type=$tn['type'];
			}

			$img->file= $file['tmp_name'];
			$img->file_dest= LAB_PATH_ROOT.lc_album_main::$basepath.$tn['path'].'/'.$name.'.'.$ext;
			$img->width=$tn['width'];
			$img->height=$tn['height'];
			if ($tn['crop']) $img->crop=$tn['crop'];
			if ($img->go())
			{
				$done[]= $img->file_dest;
				$files[$key]=lc_album_main::$basepath.$tn['path'].'/'.$name.'.'.$ext;
			}
			else
			{
				foreach($done as $file)
				{
					unlink($file);
					return LabCMS::i()->error("Ошибка генерации превью");
				}
			}
		}
		return array('name'=>$name.'.'.$ext,
					 'width'=>$img_info[0],
					 'height'=>$img_info[1],
					 'mime'=>$img_info['mime'],
					 'file'=>lc_album_main::$basepath.lc_album_main::$tn['small']['path'].'/'.$name.'.'.$ext
					 );
	}
	
	protected static function _prepareFilename($name, $ext)
	{
		$name=translit($name);
		return self::_uniqueFilename($name, $ext);
	}
	
	protected static function _uniqueFilename($name, $ext)
	{
		while(file_exists(lc_album_main::$basepath.lc_album_main::$tn['original']['path'].'/'.$name.'.'.$ext))
		{
			$name.='_1';
		}
		return $name;
	}

	public static function setImagesPath($images)
	{
		foreach($images as $key=>$image)
		{
			$images[$key]=self::setImagePath($image);
		}
		return $images;
	}
	
	public static function setImagePath($image)
	{
		foreach(lc_album_main::$tn as $key=>$item)
		{
			$image['files'][$key]=lc_album_main::$basepath.$item['path'].'/'.$image['filename'];
		}
		return $image;
	}
	
	public function getNext()
	{
		if ($image=Db::i()->selectRow("SELECT *, image_id as id FROM ?_lc_album_images WHERE album_id=? AND `sort`>? ORDER BY sort LIMIT 1", $this->album_id, $this->sort))
			return self::setImagePath($image);
	}
	
	public function getPrev()
	{
		if($image=Db::i()->selectRow("SELECT *, image_id as id FROM ?_lc_album_images WHERE album_id=? AND `sort`<? ORDER BY sort DESC LIMIT 1", $this->album_id, $this->sort))
			return self::setImagePath($image);
	}
}