<?php
namespace Modules\Admin\Config\Currencies;

class Controller extends \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing
{

	/**
	 * The list of columns which support ordering.
	 * @var array
	 */
	protected $listOrderingColumns = [];

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['insert'] 		= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['update'] 		= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['delete'] 		= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['moveUp'] 		= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['moveDown'] 		= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['save'] 			= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['reset'] 			= ['checkSection' => true, 	'checkOption' => false];
	}

	protected function optionDefineParams(\App\Mvc\View\Utils\RowOptions\Option\Option $option, $selection)
	{
		switch ($option->getId()) {
			case 'insert': case 'update':
			break;

			case 'save': case 'reset':
				if (!\App\Config\Currencies::getAdmin()->getChangedFlag()) {
					$option->setDisabled();
				}
				break;

			case 'delete':
				$selectedItem = reset($selection);
				if (\App\Config\Currencies::getAdmin()->getDefaultCurrency()==$selectedItem) {
					$option->setDisabled();
					$option->addMessage('info', $this->lang['index']['options']['reasons']['delete']['cannotDeleteDefault']);
					break;
				}
				elseif (\App\Config\Currencies::getAdmin()->getWorkCurrency()==$selectedItem) {
					$option->setDisabled();
					$option->addMessage('info', $this->lang['index']['options']['reasons']['delete']['cannotDeleteWork']);
					break;
				}

				$allRates = \App\CurrencyExchange\Date::getInstance()->getRates();
				$rates = $allRates[\App\Config\CurrencyTypes::getInstance()->getDefaultCurrencyType()];
				if ($rates and array_key_exists($selectedItem,$rates)) {
					$option->setDisabled();
					$option->addMessage('info', $this->lang['index']['options']['reasons']['delete']['cannotDeleteRate']);
					break;
				}

				break;

			case 'moveUp':
				$currencies = \App\Config\Currencies::getAdmin()->getAll();
				reset($currencies);
				$firstElement = key($currencies);
				if (in_array($firstElement, $selection)) {
					$option->setDisabled(true);
					$option->addMessage('info', $this->lang['index']['options']['reasons']['moveUp']['cannotMoveUp']);
				}
			break;

			case 'moveDown':
				$currencies = \App\Config\Currencies::getAdmin()->getAll();
				end($currencies);
				$lastElement = key($currencies);
				if (in_array($lastElement, $selection)) {
					$option->setDisabled(true);
					$option->addMessage('info', $this->lang['index']['options']['reasons']['moveDown']['cannotMoveDown']);
				}
			break;

			default:
				return false;
		}

		return true;
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::insert_getDefaultFormData()
	 */
	protected function insert_getDefaultFormData($R)
	{
		return  [];
	}


	/**
	 * Does the actual "insert" operation upon form submit.
	 */
	protected function insert_doInsert($formData, \App\MessagesCollector $msgs)
	{
		$currencyCfgAdmin = \App\Config\Currencies::getAdmin();

		$currencyArr = [
			'currencyName'=>	$formData['currency']['standard'],
			'subdivisionName'=>	$formData['subdivision']['standard'],
			'currencyName2'=>	$formData['currency']['local'],
			'subdivisionName2'=>$formData['subdivision']['local']
		];

		try {
			$currencyCfgAdmin->itemInsert($currencyArr['currencyName'], $currencyArr);
			$msgs->addSuccess($this->lang['insert']['successMessage']);
			$this->insertIdRecord = $currencyArr['currencyName'];
			return true;
		}
		catch (\App\Config\MessageException $e) {
			$msgs->addWarning(sprintf($this->lang['insert']['errorMessage'], $e->getMessage()));
			return false;
		}
	}


	/**
	 * Returns an array of default values for "update" form.
	 * @return Array
	 */
	protected function update_getDefaultFormData($id)
	{
		$currency = \App\Config\Currencies::getAdmin()->get($id);

		$formData = [];
		$formData['currency']['standard'] =		$currency['currencyName'];
		$formData['subdivision']['standard'] =	$currency['subdivisionName'];
		$formData['currency']['local'] =		$currency['currencyName2'];
		$formData['subdivision']['local'] =		$currency['subdivisionName2'];

		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::update_createEntityObject()
	 */
	protected function update_doUpdate($formData, \App\MessagesCollector $msgs)
	{

		$currencyCfg = \App\Config\Currencies::getAdmin();

		$arrayCurrency = [
			'currencyName'=>	$formData['id'],
			'subdivisionName'=>	$formData['subdivision']['standard'],
			'currencyName2'=>	$formData['currency']['local'],
			'subdivisionName2'=>$formData['subdivision']['local']
		];

		try {

			$currencyCfg->itemUpdate($formData['id'], $arrayCurrency);
			// show success message
			$msgs->addSuccess($this->lang['update']['successMessage']);
			return true;

		}
		catch (\App\Config\MessageException $e) {

			// show error message
			$msgs->addWarning(sprintf($this->lang['update']['errorMessage'], $e->getMessage()));
			return false;

		}

	}


	/**
	 * Save the changes in currencies
	 * @param array $R
	 */
	protected function actionSave($R)
	{

		$msgs = \App\MessagesCollector::create();

		$currenciesCfg = \App\Config\Currencies::getAdmin();
		try {

			$currenciesCfg->save();
			$msgs->addSuccess($this->lang['save']['successMessage']);

		}
		catch (\App\Config\MessageException $e) {

			$msgs->addError($e->getMessage());

		}

		$R['listing']['options'] = [
			'render' => 'json',
			'section' => ['bulk', 'global', ],
		];
		$response = $this->actionListRecords($R);
		$response->headers->loadMessages($msgs);

		return $response;
	}


	/**
	 * Reset the changes in currencies
	 * @param array $R
	 */
	protected function actionReset($R)
	{

		$msgs = \App\MessagesCollector::create();

		$recordsIds = $this->getListingSelection()->getList();
		if ($R['listing']['selection']) {
			$recordsIds = $this->setListingSelection($R['listing']['selection'])->getList();
		}

		$currenciesCfg = \App\Config\Currencies::getAdmin();

		try {

			$currenciesCfg->reset();
			foreach ($recordsIds as $id ) {
				$this->getListingSelection()->delete([$id]);
			}
			$msgs->addSuccess($this->lang['reset']['successMessage']);

		}
		catch (\App\Config\MessageException $e) {

			$msgs->addError($e->getMessage());

		}

		$R['listing']['options'] = [
			'render' => 'json',
			'section' => ['bulk', 'global', ],
		];
		$response = $this->actionListRecords($R);
		$response->headers->loadMessages($msgs);

		return $response;
	}


	/**
	 * Move currency up
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionMoveUp(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{

		//first order the codes as they appear inside the configuration
		$orderedIds = [];
		foreach(\App\Config\Currencies::getAdmin()->getAll() as $code => $details) {

			if (in_array($code,$recordsIds)) {
				$orderedIds[] = $code;
			}

		}

		foreach ($orderedIds as $code) {

			try {

				\App\Config\Currencies::getAdmin()->itemMoveUp($code);
				if (count($orderedIds)>1) {
					$msgs->addSuccess($this->lang['moveUp']['messages']['successMessage']);
				}

			}
			catch (\App\Config\MessageException $e) {

				$msgs->addError($e->getMessage());

			}

		}
		$msgs->groupMessagesByTypeAndText();
	}

	/**
	 * Move currency down
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionMoveDown(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		//first order the codes as they appear inside the configuration
		$order = [];
		foreach(\App\Config\Currencies::getAdmin()->getAll()as $code => $details) {

			if (in_array($code,$recordsIds)) {
				$order[] = $code;
			}

		}

		// then reverse them as we are moving them down
		$orderedIds = array_reverse($order);

		foreach ($orderedIds as $code) {
			try {

				\App\Config\Currencies::getAdmin()->itemMoveDown($code);
				if (count($orderedIds)>1) {
					$msgs->addSuccess($this->lang['moveDown']['messages']['successMessage']);
				}

			}
			catch (\App\Config\MessageException $e) {

				$msgs->addError($e->getMessage());

			}
		}
		$msgs->groupMessagesByTypeAndText();
	}


	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::delete_doDelete()
	 */
	protected function delete_doDelete(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		$currenciesCfg = \App\Config\Currencies::getAdmin();

		foreach ($recordsIds as $record) {

			try {

				$currenciesCfg->itemDelete($record);
				// remove this record from the internal list
				$this->getListingSelection()->delete([$record]);
				$msgs->addSuccess($this->lang['delete']['successMessage']);

			}
			catch (\App\Config\MessageException $e) {

				$msgs->addError($e->getMessage());

			}
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionGetEntityName()
	 */
	protected function optionGetEntityName($id)
	{
		$item = \App\Config\Currencies::getAdmin()->get($id);
		return $item['name'];
	}
}