<?php

namespace Entity;

class Validator_UserProfile extends \App\Entity\Utils\Extension_ValidateDefaultAbstract
{
	/**
	 * Validate name for insert
	 */
	protected function check_insert()
	{
		// get current fields details
		$fields = $this->entity->getFields();

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

		// check if name field is not empty
		if ($fields['name']) {

			$userProfileObj = new \App\EntityList\UserProfiles();
			$userProfileObj->setFilter('userProfile.name', 'LIKE', $fields['name']);
			$userProfileObj->setLimit(1);
			$userProfileArray = $userProfileObj->exportRecords();

			// check if name is unique
			if ($userProfileArray) {
				$currentMessages->addWarningCode('insert_nameNotUnique');
			}
		}
	}

	/**
	 * 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 records
		$userProfile = UserProfile::selectForUpdate($currentEntityId);

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

	/**
	 * Validate the field 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 (array_key_exists('name', $fields)) {
			$userProfileObj = new \App\EntityList\UserProfiles();
			$userProfileObj->setFilter('userProfile.name', 'LIKE', $fields['name']);
			$userProfileObj->setFilter('userProfile.id', '!=', $currentEntityId);
			$userProfileObj->setLimit(1);

			$userProfileArray = $userProfileObj->exportRecords();

			// check if name is unique
			if ($userProfileArray) {
				$currentMessages->addWarningCode('update_nameNotUnique');
			}
		}
	}

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

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

		// check if task category is not already deleted
		$userProfile = UserProfile::selectForUpdate($currentEntityId);

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

		$userObj = new \App\EntityList\Users();
		$userObj->setFilter('user.idUsersAccessProfile', 'LIKE', $currentEntityId);
		$userObj->setLimit(1);

		$userArray = $userObj->exportRecords();
		if ($userArray) {
			$currentMessages->addWarningCode('delete_profHasUsers');
		}
	}
}
