<?php

namespace Modules\Admin\Config\Documents\IssueDocs;

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\IssueDocuments::getAdmin()->getChangedFlag()) {
					$option->setDisabled();
				}
				break;
			}

			case 'delete': {
				$existingDocs = \App\Config\IssueDocuments::getInstance()->getAll();
				if (array_intersect(array_keys($existingDocs), $selection)) {
					$option->setDisabled();
					$option->addMessage('info', $this->lang['delete']['cannotDeletePrevDoc']);
				}
				break;
			}


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

			case 'moveDown': {
				$docTypes = \App\Config\IssueDocuments::getAdmin()->getAll();
				end($docTypes);
				$lastElement = key($docTypes);
				if (in_array($lastElement, $selection)) {
					$option->setDisabled(true);
					$option->addMessage('info', $this->lang['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)
	{

		$issueDocsCfgAdmin = \App\Config\IssueDocuments::getAdmin();

		$issueDocDetails = [
			'code'					=> $formData['id'],
			'name'					=> $formData['name'],
			'active'				=> $formData['active'],
			'pivot'					=> $formData['pivot'],
			'mainDocOnPivot'		=> $formData['mainDocOnPivot'],
			'docCategory'			=> $formData['docCategory'],
			'docNumberType'			=> $formData['docNumberType'],
			'numberReuse'			=> $formData['numberReuse'],
			'docDate'				=> $formData['docDate'],
			'forceSameTemplate'		=> $formData['forceSameTemplate'],
			'maxGenerationCount'	=> $formData['maxGenerationCount'],
			'autoGenerateFirstCopy'	=> $formData['autoGenerateFirstCopy'],
			'printOriginalOnce'		=> $formData['printOriginalOnce'],
			'indicateCopy'			=> $formData['indicateCopy'],
			'serviceTypes'			=> (array)$formData['serviceTypes'],
		];

		try {
			$issueDocsCfgAdmin->itemInsert($formData['id'], $issueDocDetails);
			$msgs->addSuccess($this->lang['insert']['successMessage']);
			$this->insertIdRecord = $formData['id'];
			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)
	{
		$issueDoc = \App\Config\IssueDocuments::getAdmin()->get($id);

		$formData['id']						= $issueDoc['code'];
		$formData['name']					= $issueDoc['name'];
		$formData['active']					= $issueDoc['active'];
		$formData['pivot']					= $issueDoc['pivot'];
		$formData['mainDocOnPivot']			= $issueDoc['mainDocOnPivot'];
		$formData['docCategory']			= $issueDoc['docCategory'];
		$formData['docNumberType']			= $issueDoc['docNumberType'];
		$formData['numberReuse']			= $issueDoc['numberReuse'];
		$formData['docDate']				= $issueDoc['docDate'];
		$formData['forceSameTemplate']		= $issueDoc['forceSameTemplate'];
		$formData['maxGenerationCount']		= $issueDoc['maxGenerationCount'];
		$formData['autoGenerateFirstCopy']	= $issueDoc['autoGenerateFirstCopy'];
		$formData['printOriginalOnce']		= $issueDoc['printOriginalOnce'];
		$formData['indicateCopy']			= $issueDoc['indicateCopy'];
		$formData['serviceTypes']			= $issueDoc['serviceTypes'];

		return $formData;
	}

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

		$issueDocsCfgAdmin = \App\Config\IssueDocuments::getAdmin();

		$issueDocDetails = [
			'name'					=> $formData['name'],
			'active'				=> $formData['active'],
			'pivot'					=> $formData['pivot'],
			'mainDocOnPivot'		=> $formData['mainDocOnPivot'],
			'docCategory'			=> $formData['docCategory'],
			'docNumberType'			=> $formData['docNumberType'],
			'numberReuse'			=> $formData['numberReuse'],
			'docDate'				=> $formData['docDate'],
			'serviceTypes'			=> (array)$formData['serviceTypes'],
			'forceSameTemplate'		=> $formData['forceSameTemplate'],
			'maxGenerationCount'	=> $formData['maxGenerationCount'],
			'autoGenerateFirstCopy'	=> $formData['autoGenerateFirstCopy'],
			'printOriginalOnce'		=> $formData['printOriginalOnce'],
			'indicateCopy'			=> $formData['indicateCopy'],
		];

		try {

			$issueDocsCfgAdmin->itemUpdate($formData['id'], $issueDocDetails);
			// 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;

		}

	}

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

		foreach ($recordsIds as $docCode) {

			try {

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

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

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

			}
		}

	}


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

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

		$issueDocsCfg = \App\Config\IssueDocuments::getAdmin();
		try {

			$issueDocsCfg->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.
	 * @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();
		}

		$issueDocsCfg = \App\Config\IssueDocuments::getAdmin();

		try {
			$issueDocsCfg->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 doc type 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\IssueDocuments::getAdmin()->getAll() as $code => $details) {

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

		}

		foreach ($orderedIds as $code) {

			try {

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

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

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

			}

		}

		$msgs->groupMessagesByTypeAndText();

	}

	/**
	 * Move doc type 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\IssueDocuments::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\IssueDocuments::getAdmin()->itemMoveDown($code);
				if (count($orderedIds)>1) {
					$msgs->addSuccess($this->lang['moveDown']['successMessage']);
				}

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

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

			}
		}

		$msgs->groupMessagesByTypeAndText();

	}


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