<?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_images
{
	public $page=1;
	public $total=0;
	public $items_at_page=16;
	public $pager=array();
	public $orderby='sort';
	
	function __construct()
	{
		if (intval(config::get('items_at_page'))) $this->items_at_page=intval(config::get('items_at_page'));
	}
	
	public function getListByAlbum($album, $page=1)
	{
		if ($page) $this->page=$page;
		if (!$this->total) {
			$this->total=Db::i()->selectCell(
				"SELECT COUNT(*) FROM ".config::get('table_images')." WHERE album_id=?", $album->id
			);
		}
		if ($this->total) {
			$result=array();
			$start=$this->_getStart();
			$images=Db::i()->select(
				"SELECT * FROM ".config::get('table_images')." {WHERE album_id=? }ORDER BY ".$this->orderby." LIMIT ?d, ?d",
				$album->id,
				$start,
				$this->items_at_page
			);
			if ($images) {
				foreach ($images as $key=>$image) {
					$result[$key]=Factory::create('lc_album.image');
					$result[$key]->set($image);
					$result[$key]->setAlbum($album);
				}
				
				return $result;
			}
			
		}
	}
	
	protected function _getStart()
	{
		$pg=Factory::create('Paginator', $this->total, $this->items_at_page, $this->page);
		$this->pager=$pg->getPages();
		$this->page=$this->pager['current'];
		return $this->pager['sql_start'];
	}
	
	public function setSort($files)
	{
		if ($files) foreach ($files as $image_id=>$sort) {
				Db::i()->query(
					"UPDATE ".config::get('table_images')." SET sort=? WHERE image_id=?", $sort, $image_id
				);
		}
	}

}