<?php

/**
 * Clients for Contao
 *
 * Copyright (c) 2014 Benjamin Roth [http://www.esales-media.de]
 *
 * @package eSM_clients
 * @link    http://www.esales-media.de
 * @license commercial
*/


/**
 * Run in a custom namespace, so the class can be replaced
 */
namespace eSM_clients;


/**
 * Shows a list of clients which have active projects
 *
 * @package   Modules
 * @author    Benjamin Roth <http://www.esales-media.de>
 * @copyright eSales Media 2014
 */
class ModuleClientsProjectDevices extends \Module
{
	/**
	 * Template
	 * @var string
	 */
	protected $strTemplate = 'mod_clientsProjectDevices';

	protected $objProject = null;

	protected $arrSRCs = array();
	protected $referenceHeight;


	public function generate()
	{
		if (TL_MODE == 'BE')
		{
			$objTemplate = new \BackendTemplate('be_wildcard');

			$objTemplate->wildcard = '### ' . utf8_strtoupper($GLOBALS['TL_LANG']['FMD']['clientsProjectDevices'][0]) . ' ###';
			$objTemplate->title = $this->headline;
			$objTemplate->id = $this->id;
			$objTemplate->link = $this->name;
			$objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;

			return $objTemplate->parse();
		}

		// Set the item from the auto_item parameter
		if (!isset($_GET['items']) && \Config::get('useAutoItem') && isset($_GET['auto_item']))
		{
			\Input::setGet('items', \Input::get('auto_item'));
		}

		$this->objProject = EsmClientsProjectsModel::findByIdOrAlias($_GET['items']);

		if ($this->objProject === null)
		{
			global $objPage;
			$objHandler = new $GLOBALS['TL_PTY']['error_404']();
			$objHandler->generate($objPage->id);
		}

		// Selected devices
		$this->esm_clients_devices = deserialize($this->esm_clients_devices, true);

		// Collect device images
		if ($this->objProject->desktopSRC != '' && in_array('desktop', $this->esm_clients_devices))
		{
			$this->arrSRCs['desktop'] = $this->objProject->desktopSRC;
		}

		if ($this->objProject->phoneSRC != '' && in_array('smartphone', $this->esm_clients_devices))
		{
			$this->arrSRCs['phone'] = $this->objProject->phoneSRC;
		}

		if ($this->objProject->tabletSRC != '' && in_array('tablet', $this->esm_clients_devices))
		{
			$this->arrSRCs['tablet'] = $this->objProject->tabletSRC;
		}

		// Don't show module if no device screen is available
		if (!count($this->arrSRCs))
		{
			return '';
		}

		// Load CSS
		$GLOBALS['TL_CSS'][] = 'system/modules/eSM_clients/assets/css/devices.css||static';


		return parent::generate();
	}

	/**
	 * Compile the current element
	 */
	protected function compile()
	{
		global $objPage;

		$this->esm_clients_devices_dimensions = deserialize($this->esm_clients_devices_dimensions);
		if ($this->esm_clients_devices_dimensions[1])
		{
			$this->referenceHeight = $this->esm_clients_devices_dimensions[1];
			$this->Template->referenceHeight = $this->referenceHeight;
		}

		// Add images
		$arrDeviceScreenshots = array();
		foreach ($this->arrSRCs as $devicetype => $source)
		{
			$objModel = \FilesModel::findByUuid($source);

			if ($objModel === null)
			{
				if (!\Validator::isUuid($source))
				{
					$this->Template->text = '<p class="error">'.$GLOBALS['TL_LANG']['ERR']['version2format'].'</p>';
				}
			}
			elseif (is_file(TL_ROOT . '/' . $objModel->path))
			{
				// Calculate devicemask height
				if (isset($GLOBALS['eSM_clients']['devices'][$devicetype]))
				{
					$objDevicemask = new \File($GLOBALS['eSM_clients']['devices'][$devicetype]['devicemask']['imageSRC'], true);
					if ($objDevicemask->isImage)
					{
						$intDeviceHeight = round($this->referenceHeight * $GLOBALS['eSM_clients']['devices'][$devicetype]['devicemask']['ratio']);
						$objDevicemaskImage = \Image::create($objDevicemask,array('',$intDeviceHeight,'proportional'));
						$objDevicemask = new \File($objDevicemaskImage->executeResize()->getResizedPath(),true);
					}
				}

				$objFile = new \File($objModel->path,true);
				if ($objFile->isImage)
				{
					$arrMeta = \Frontend::getMetaData($objModel->meta, $objPage->language);
					$arrImage = array
					(
						'id'        => $objModel->id,
						'uuid'      => $objModel->uuid,
						'name'      => $objFile->basename,
						'singleSRC' => $objModel->path,
						'alt'       => $arrMeta['title'],
						'imageUrl'  => $arrMeta['link'],
						'caption'   => $arrMeta['caption'],
						'size'      => serialize(array($objDevicemask->width*$GLOBALS['eSM_clients']['devices'][$devicetype]['screen']['ratio']['x'],$objDevicemask->height*$GLOBALS['eSM_clients']['devices'][$devicetype]['screen']['ratio']['y'],'center_top')),
					);
					$objImage = new \stdClass();
					$this->addImageToTemplate($objImage, $arrImage);
					$arrDeviceScreenshots[$devicetype] = array
					(
						'device'     => $objDevicemask->path,
						'screenshot' => $objImage
					);
				}
			}
		}

		// Add images to Template
		$this->Template->screenshots = $arrDeviceScreenshots;

	}
}