<?php

/**
 * Description of Gallery_Controller_IndexController
 *
 * @author dmastylak
 */
class Gallery_Controller_IndexController extends Core_Controller_IndexController {

	public function indexAction() {

        $gallery = self::getGaleries();

        $this->view->gallery = $gallery;
    }
    
    public function showAction() {

        $images = R::find('image', 'galleryid = ? ORDER BY o ASC', [''.$this->_getParam('id').'']);

	$this->view->gallery = R::findOne('gallery', 'active = 1 AND id = ?', [''.$this->_getParam('id').'']);
        $this->view->images = $images;
	$this->view->imagePath = '/modules/Gallery/front/images/';
    }
    
    

    public static function getGaleries() {
        $galleries = R::find('gallery', 'active = 1 ORDER BY id DESC');

        return $galleries;
    }

    public function getThumbAction() {
        $gallery = R::findOne('gallery', 'id = ?', ['' . $this->_getParam('id') . '']);
        $targetDir = Gallery_Gallery_Storage::factory($gallery)->getPath();

        $fileName = 'img.jpg';

        Rtn_ImageWc::generate($targetDir . $fileName, 300, 300);
    }

    /**
     * Pobieranie jednej galerii
     * 
     * @param int $id
     * @return obiect
     */
    public static function getOneGallery($id) {
        $gallery = R::findOne('gallery', $id);

        $images = R::find('image', 'galleryid = ? ORDER BY o ASC', [$id]);

        return ['gallery' => $gallery, 'images' => $images];
    }

    /**
     * Pobieranie wszystkich aktywnych galerii
     * 
     * @return obiect
     */
    public static function getAllGallery() {
        $sql = 'SELECT gallery.*, image.id as img_id FROM gallery 
        JOIN image WHERE image.galleryid = gallery.id';
        $rows = R::getAll($sql);

        foreach ($rows as $key => $value) {
            $newarray[$value['id']][$key] = $value;
        }

        return $newarray;
    }

    /**
     * Pobieranie zdjęcia po id
     */
    public function getImageAction() {
        $gallery = R::findOne('image', 'id = ?', array($this->_getParam('id')));

        $targetDir = Gallery_Image_Storage::factory($gallery)->getPath();

        $fileName = 'img.jpg';

        Rtn_ImageWc::generate($targetDir . $fileName, 180, 135);
    }

}
