<?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 extends DefaultObject
{
	protected $allowed_keys=array(
		'album_id', 'name', 'describe', 'filename', 'sort', 'updated', 'total_votes', 'vote_result', 'rating'
	);
	
	public $album=null;
	
	public function __construct($image_id=null)
	{
		$this->data['id']=&$this->data['image_id'];
		if ($image_id) {
			$this->loadDataById($image_id);
		}
	}
	
	public function __set($key, $value)
	{
		parent::__set($key, $value);
		if ('describe'==$key) {
			parent::__set('describe_html', getbb($value));
		} elseif ('filename'==$key) {
			$this->setImagePath($value);
		}
	}
	
	public function loadDataById($image_id)
	{
		$image=Db::i()->selectRow(
			"SELECT *, image_id as id
			FROM ".config::get('table_images')." WHERE image_id=?", $image_id
		);
		if (!$image) return false;
		$this->set($image);
		$this->setAlbum($this->_getAlbum($this->album_id));
		unset($image);
		return $this;
	}

	public function addImage($data, $album_id)
	{
		if ($info=$this->_uploadImage($data['Filedata'])) {
			$info['image_id']=Db::i()->query(
				"INSERT INTO ".config::get('table_images')." 
				(album_id, filename) 
				VALUES(?, ?)",
				$album_id,
				$info['name']
			);
			Db::i()->query("UPDATE ".config::get('table_images')." SET sort=image_id WHERE image_id=?", $info['image_id']);
			$info['url']=_url($info['image_id'], 'image');
			return $info;
		}
	}
	
	public function editImage($data)
	{
		if ($data['Filedata']['tmp_name']) {
			$fileinfo=$this->_uploadImage($data['Filedata']);
			if ($fileinfo && $fileinfo['name']!=$this->filename) $this->deleteFiles($this->filename);
		}

		$update=array(
			'name'=>$data['name'],
			'describe'=>$data['describe'],
			'album_id'=>$data['album_id'],
		);
		if ($fileinfo) $update['filename']=$fileinfo['name'];
		
		$this->update($update);

		if ($this->album_id!=$data['album_id']) {
			Db::i()->query(
				"UPDATE ".config::get('table_images')."
				SET `sort`=
				(SELECT `sort`
				FROM (SELECT MAX(sort)+1 as `sort` FROM ".config::get('table_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 ".config::get('table_images')." WHERE image_id=?", $this->id);
		$this->deleteFiles($this->filename);
	}
	
	public function vote($vote)
	{
		//TODO убрать тип в свойства  объекта
		$data=array(
			'item_id'=>$this->id,
			'type'=>2, //тип - фото
			'user_id'=>0, //фотографии к пользователям не привязаны
			'total_votes'=>$this->total_votes,
			'vote_result'=>$this->vote_result,
			'rating'=>$this->rating,
			'vote'=>$vote
		);
		
		$voter=Rating_Generic::init();
		$voter->vote($data);
		
		if (LabCMS::i()->no_errors) {
			$this->update(
				array(
					'total_votes'=>$data['total_votes'],
					'vote_result'=>$data['vote_result'],
					'rating'=>$data['rating']
				)
			);

			return $data;
		}
	}
	
	public function getArray()
	{
		return $this->data;
	}
    
	public function deleteFiles($filename)
	{
		foreach (config::get('tn') as $tn) {
			unlink(LAB_PATH_ROOT.config::get('basepath').$tn['path'].'/'.$filename);
		}
	}
	
	protected function _uploadImage($file)
	{
		foreach (config::get('tn') as $tn)
			if (!is_dir(LAB_PATH_ROOT.config::get('basepath').$tn['path']))
				mkdir(LAB_PATH_ROOT.config::get('basepath').$tn['path'], 0777, true);
			
		$img_info=getimagesize($file['tmp_name']);
		if (!($img_info[2]>0 && $img_info[2]<4)) return LabCMS::i()->error(_m('Недопустимый формат файла'));
		
		$name=preg_replace('/\.[^.]+$/', '', $file['name']);
		$ctn=config::get('tn');
		if ($ctn['original']['type']) $def_ext=$ctn['original']['type'];
		else $def_ext=image_type_to_extension($img_info[2], false);
		$name=$this->_prepareFilename($name, $def_ext);
		
		foreach (config::get('tn') as $key=>$tn) {
			$folder=$tn['path'];
			$img=Factory::create('Image_Resize');
			if ($tn['type']) {
				$ext=$img->new_type=$tn['type'];
			} else {
				$ext=$def_ext;
			}

			$img->file= $file['tmp_name'];
			$img->file_dest= LAB_PATH_ROOT.config::get('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]=config::get('basepath').$tn['path'].'/'.$name.'.'.$ext;
			} else {
				foreach ($done as $file) {
					unlink($file);
					return LabCMS::i()->error(_m('Ошибка генерации превью'));
				}
			}
		}
		
		if ($tn['small']['type']) $ext=$tn['small']['type'];
		else $ext=$def_ext;
		
		return array(
			'name'=>$name.'.'.$ext,
			'thumbnailUrl'=>config::get('basepath').$ctn['small']['path'].'/'.$name.'.'.$ext,
			'width'=>$img_info[0],
			'height'=>$img_info[1],
			'mime'=>$img_info['mime'],
			'type'=>$img_info['mime'],
			'size'=>$file['size'],
			'file'=>config::get('basepath').$ctn['small']['path'].'/'.$name.'.'.$ext
		);
	}
	
	protected function _prepareFilename($name, $ext)
	{
		$name=translit($name);
		return $this->_uniqueFilename($name, $ext);
	}
	
	protected function _uniqueFilename($name, $ext)
	{
		$ctn=config::get('tn');
		while (file_exists(LAB_PATH_ROOT.config::get('basepath').$ctn['original']['path'].'/'.$name.'.'.$ext)) {
			$name.='_1';
		}
		return $name;
	}

	public function setImagePath()
	{
		$this->files=array();
		foreach (config::get('tn') as $key=>$item) {
			$this->files[$key]=config::get('basepath').$item['path'].'/'.$this->filename;
		}
	}
	
	public function getNext()
	{
		if (
			$data=Db::i()->selectRow(
				"SELECT *
				FROM ".config::get('table_images')."
				WHERE album_id=? AND `sort`>?
				ORDER BY sort
				LIMIT 1", $this->album_id, $this->sort
			)
		) {
			$img=Factory::create('lc_album.image');
			$img->set($data);
			$img->setAlbum($this->album);
			return $img;
		}
	}
	
	public function getPrev()
	{
		if (
			$data=Db::i()->selectRow(
				"SELECT *
				FROM ".config::get('table_images')."
				WHERE album_id=? AND `sort`<?
				ORDER BY sort DESC LIMIT 1",
				$this->album_id, $this->sort
			)
		) {
			$img=Factory::create('lc_album.image');
			$img->set($data);
			$img->setAlbum($this->album);
			return $img;
		}
	}
	
	public function setAlbum($album)
	{
		$this->album=$album;
	}
	
	protected function _getAlbum($album_id)
	{
		//TODO добавить обработчик ошибок
		return Factory::create('lc_album.album', $album_id);
	}
	
	protected function _updateDB(&$data)
	{
		return Db::i()->query(
			"UPDATE ".config::get('table_images')." SET ?a, `updated`=?d WHERE image_id=?", $data, time(), $this->id
		);
	}
	
	protected function _resetItemCache()
	{
	}

}