<?php
namespace Entity;

class Validator_TaskOperationType extends \App\Entity\Utils\Extension_ValidateDefaultAbstract
{

	/**
	 * Validate fields for insert task operation type
	 */
	protected function check_insert()
	{
		// get current fields details
		$fields = $this->entity->getFields();

		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// if description is filled check if exists another with the same description
		if ($fields['description']) {

			// use entity list for not using SELECT query
			$taskOperationTypesObj = new \App\EntityList\TaskOperationTypes();
			$taskOperationTypesObj->setFilter('taskOperationTypes.description', 'LIKE', $fields['description']);
			$taskOperationTypesArray = $taskOperationTypesObj->exportRecords();
			if ($taskOperationTypesArray) {
				$currentMessages->addWarningCode('descriptionNotUnique');
			}
		}
	}

	/**
	 * Check if update can be done
	 */
	protected function isAvailable_update()
	{
		// current entity id
		$currentEntityId = $this->entity->getId();

		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// lock record
		$taskOperationType = \Entity\TaskOperationType::selectForUpdate($currentEntityId);

		if(!$taskOperationType->recordExists()) {
			$currentMessages->addErrorCode('update_invalidId');
		}
		elseif ($taskOperationType->deleted) {
			$currentMessages->addWarningCode('update_deleted');

		}
	}

	/**
	 * Validate the fields for updating
	 */
	protected function check_update()
	{
		// get current fields details;
		$fields = $this->entity->getFields();

		// current entity id
		$currentEntityId = $this->entity->getId();

		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// if description is not empty
		if (array_key_exists('description', $fields)) {

			$taskOperationTypeObj = new \App\EntityList\TaskOperationTypes();
			$taskOperationTypeObj->setFilter('taskOperationTypes.description', 'LIKE', $fields['description']);
			$taskOperationTypeObj->setFilter('taskOperationTypes.id', '!=', $currentEntityId);
			$taskOperationTypeArray = $taskOperationTypeObj->exportRecords();
			if ($taskOperationTypeArray) {
				$currentMessages->addWarningCode('descriptionNotUnique');
			}
		}
	}

	/**
	 * Check if the operation can be performed
	 */
	protected function isAvailable_delete()
	{
		// current entity id
		$currentEntityId = $this->entity->getId();

		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// check if operation type is not already deleted
		$taskOperationType = \Entity\TaskOperationType::selectForUpdate($currentEntityId);

		if (!$taskOperationType->recordExists()) {
			$currentMessages->addErrorCode('delete_idInvalid');
		} elseif ($taskOperationType->deleted) {
			$currentMessages->addWarningCode('delete_deleted');
		}
	}
}