<?php

/**
 * Description of IndexController
 * moduł wymaga dalszych poprawek - jak będzie czas J
 *
 * @author dmastylak
 */
class Gallery_Controller_Admin_IndexController extends Eppe_Crud_Controller_Action {

	protected $grid = 'Gallery_Jqgrid_Gallery';
	protected $crud = 'Gallery_CRUD_Gallery';

	public function init() {
		parent::init();
		$this->view->headScript()->appendFile(Core_Module_Module::getInstance()->getAdminJSPath() . 'jquery-sortable.js');
	}

	public function indexAction() {
//        parent::indexAction();

		$cfg = self::_prepareConfig();

		if ($cfg['features']['multiple'] == 'false') {
			$r = new Zend_Controller_Action_Helper_Redirector;
			$r->gotoUrl('/Gallery/admin_index/edit/id/1')->redirectAndExit();
		} else {
			parent::indexAction();
		}
	}

	public function uploadAction() {
		$this->_disableView();

		// 5 minutes execution time
		@set_time_limit(5 * 60);

		// Uncomment this one to fake upload time
		// usleep(5000);
		// Settings
		//$targetDir = 'uploads';
		$cleanupTargetDir = true; // Remove old files
		$maxFileAge = 5 * 3600; // Temp file age in seconds
		// Get a file name
		if (isset($_REQUEST["name"])) {
			$fileName = $_REQUEST["name"];
		} elseif (!empty($_FILES)) {
			$fileName = $_FILES["file"]["name"];
		} else {
			$fileName = uniqid("file_");
		}

		/*		 * *********************************************************************************
		 * Zmiana ścieżki i nazwy pliku
		 * ******************************************************************************** */
		$targetDir = null;
		$image = R::dispense('image');

		$image->galleryid = $this->_getParam('id');
//        $image->path = $targetDir . $fileName;
		$image->created = New DateTime();

		$id = R::store($image);

//                $targetDir = Gallery_Image_Storage::factory($image)->getPath();
		$targetDir = PUBLIC_PATH . 'modules/Gallery/front/images/' . $id;
//        $size = getimagesize($targetDir . $fileName);
		//Rtn_ImageWc::generate($targetDir.$fileName, $size[0], $size[1]);

		$fileName = 'img.jpg';

		//*****************************************************************************//
		// Create target dir
		if (!file_exists($targetDir)) {
			@mkdir($targetDir);
		}



		$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

		// Chunking might be enabled
		$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
		$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;


		// Remove old temp files	
		if ($cleanupTargetDir) {
			if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
			}

			while (($file = readdir($dir)) !== false) {
				$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

				// If temp file is current file proceed to the next
				if ($tmpfilePath == "{$filePath}.part") {
					continue;
				}

				// Remove temp file if it is older than the max age and is not the current file
				if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
					@unlink($tmpfilePath);
				}
			}
			closedir($dir);
		}


		// Open temp file
		if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
			die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream.?"}, "id" : "id"}');
		}

		if (!empty($_FILES)) {
			if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
			}

			// Read binary input stream and append it to temp file
			if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
			}
		} else {
			if (!$in = @fopen("php://input", "rb")) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
			}
		}

		while ($buff = fread($in, 4096)) {
			fwrite($out, $buff);
		}

		@fclose($out);
		@fclose($in);

		// Check if file has been uploaded
		if (!$chunks || $chunk == $chunks - 1) {
			// Strip the temp .part suffix off 
			rename("{$filePath}.part", $filePath);

			$thumb = PhpThumb_PhpThumbFactory::create($filePath);
			$thumb->resize(180);
			$thumb->cropFromTopCenter(180, 119);
			$thumb->save($targetDir . DIRECTORY_SEPARATOR . 'img-thumb.jpg');

			$thumb2 = PhpThumb_PhpThumbFactory::create($filePath);
			$thumb2->resize(100);
			$thumb2->save($targetDir . DIRECTORY_SEPARATOR . 'img-100x100.jpg');
			
		}



		// Return Success JSON-RPC response
//        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
	}

	/**
	 * Pobieranie zdjęcia po id
	 */
	public function getImageAction() {
//		$gallery = R::findOne('image', 'id = ?', array($this->_getParam('id')));

//		$targetDir = Gallery_Image_Storage::factory($gallery)->getPath();
		$targetDir = PUBLIC_PATH . 'modules/Gallery/front/images/' . $this->_getParam('id');

		$fileName = '/img-100x100.jpg';

		$thumb = PhpThumb_PhpThumbFactory::create($targetDir . $fileName);
		$thumb->show();
	}

	/**
	 * Usuwanie zdjęcia i katalogu
	 */
	public function removeImageAction() {
		$this->_disableView();

		$gallery = R::findOne('image', 'id = ?', array($this->_getParam('id')));
		
		$targetDir = PUBLIC_PATH . 'modules/Gallery/front/images/' . $this->_getParam('id');
//		$targetDir = Gallery_Image_Storage::factory($gallery)->getPath();

		R::trash($gallery);

		unlink($targetDir . '/img.jpg');
		unlink($targetDir . '/img-thumb.jpg');
		unlink($targetDir . '/img-100x100.jpg');
		rmdir($targetDir);

		exit;
	}

	/**
	 * Pobieranie galerii
	 */
	public function getAction() {
		$this->_disableView();

		$gallery = R::findOne('gallery', $this->_getParam('id'));
		$images = R::findAll('image', 'galleryid = ? ORDER BY o ASC', array($this->_getParam('id')));

		foreach ($images as $img) {
//			echo '<li id="' . $img->id . '"><img src="/Gallery/admin_index/get-image/id/' . $img->id . '/img.jpg" style="width: 100px; margin:10px;" /><br/>';
			echo '<li id="' . $img->id . '"><div style="height:100px"><img src="/modules/Gallery/front/images/' . $img->id .'/img-100x100.jpg" style="width: 100px; margin:10px;" /></div><br/>';
			echo '<span style="display:none">' . $img->id . '</span>'
			. '<button class="button remove-image" type="submit" nr="' . $img->id . '" id="button-submit" name="submit">usuń</button></li>';
		}

		exit;
	}

	/**
	 * Zapis kolejności w galerii
	 */
	public function saveOrderAction() {
		$i = 1;

		foreach ($_POST['order'] as $order) {
			$img = null;

			$img = R::findOne('image', 'id = ?', [$order]);

			$img->o = $i;
			R::store($img);

			$i++;
		}
	}

	public function getThumbGalleryAction() {
		$gallery = R::findOne('gallery', 'id = ?', array($this->_getParam('id')));

		$targetDir = Gallery_Gallery_Storage::factory($gallery)->getPath();

		$fileName = 'img.jpg';

		$size = getimagesize($targetDir . $fileName);

		Rtn_ImageWc::generate($targetDir . $fileName, $size['0'], $size['1']);
	}

	public function editAction() {
		$beanId = $this->_getParam('id');
		if (!$this->isAjax) {
			$this->view->bean_id = $beanId;
			if ($this->_edit($beanId)) {

				$r = new Zend_Controller_Action_Helper_Redirector;
				$r->gotoUrl('/Gallery/admin_index/index')->redirectAndExit();
			}
		} else {

			$this->_edit($beanId);
		}
		$gallery = R::findOne('gallery', 'id = ?', [$beanId]);
		$target = Gallery_Gallery_Storage::factory($gallery)->getPath();

		$this->view->thumbGallery = $target;
	}

	protected function _edit($beanId) {
		$bean = $this->crud->findBean($beanId);

		$formClassName = $this->crud->getFormClassName();

		$form = new $formClassName(['bean' => $bean]);

		if ($this->_isPost()) {

			$post = $this->_getPost();

			if (isset($post['cancel'])) {
				$this->_redirectIndex();
			}

			if ($form->isValid($post)) {

				if ($form->thumb->isUploaded()) {
					$targetDir = Gallery_Gallery_Storage::factory($bean)->getPath();
					if (file_exists($targetDir . 'img.jpg')) {
						unlink($targetDir . 'img.jpg');
					}
					$adapter = new Zend_File_Transfer_Adapter_Http();

					$adapter->setDestination($targetDir);
					$adapter->addFilter('Rename', $targetDir . 'img.jpg');

					if (!$adapter->receive()) {
						$messages = $adapter->getMessages();
					}
				}
				if ($this->crud->update($beanId, $post)) {
					$this->_addMessage(__('Zmiany zostały zapisane'));
					$this->_redirectIndex();
				}
			} else {
				$form->populate($this->_getPost());
			}
		} else {
			$form->populateWithBean($bean);
		}


		$this->view->form = $form;
	}

	/**
	 * Odczytuje konfiguracja modułu 
	 */
	static function _prepareConfig() {
		$filename = APPLICATION_PATH . '/modules/Gallery/configs/module.ini';

		$t = new Zend_Config_Ini($filename, 'production');

		return $t->toArray();
	}

}
