<?php

namespace App\Config;

class WebhookQueue extends SystemVars
{
	/**
	 * The vars prefix in systemVars db table
	 * @var String
	 */
	protected $dbVarsPrefix = 'webhookQueue_';

	/**
	 * (non-PHPdoc)
	 * @see \App\Config\BaseAbstract::constructInit()
	 */
	protected $dbVarsList = [ 'enabled', 'url', 'username', 'password', 'activeEntityActions', 'autoQueueEntityActions'];


	/**
	 * All allowed entity actions.
	 * @var array
	 */
	private $allEntityActions = [
		'Corporate'			=> [ 'insert', 'update', 'delete' ],
		'Customer'			=> [ 'insert', 'update', 'delete' ],
		'Supplier'			=> [ 'insert', 'update', 'delete' ],
		'Service'			=> [ 'insert', 'update', 'statusOp', 'statusFin', 'cashedStatus' ],
		'Invoice'			=> [ 'insert', 'update', 'issue', 'cancel', 'cashedStatus' ],
		'InvoiceCashing'	=> [ 'insert', 'update', 'issue', 'cancel', 'blockStatus' ],
		'Document'			=> [ 'insert' ],
	];

	/**
	 * Returns all entities and actions (the original structure.
	 * @return array
	 */
	public function getAllEntityActions()
	{
		return $this->allEntityActions;
	}

	/**
	 * Checks if the entity is valid.
	 * @param string $entity
	 * @return boolean
	 */
	public function entityTypeValid(string $entity) : bool
	{
		return array_key_exists($entity, $this->allEntityActions);
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Config\BaseAbstract::save_check()
	 */
	protected function save_check()
	{
		// general validations
		parent::save_check();

		// CHECK activeEntityActions --------------------------------------------------------------
		$activeEntActions = $this->getActiveEntityActions();
		foreach ($activeEntActions as $entity => $actions) {
			if (!$this->entityTypeValid($entity)) {
				$this->addErrorMessage("The entity type `{$entity}` is not valid for active entities.");
			} else {
				foreach ($actions as $action) {
					if (!in_array($action, $this->allEntityActions[$entity])) {
						$this->addErrorMessage("The entity action `{$entity}-{$action}` is not valid for active entities.");
					}
				}
			}
		}

		// CHECK autoQueueEntityActions --------------------------------------------------------------
		$autoQueueEntActions = $this->getAutoQueueEntityActions();
		foreach ($autoQueueEntActions as $entity => $actions) {
			if (!$this->entityTypeValid($entity)) {
				$this->addErrorMessage("The entity type `{$entity}` is not valid for auto-queue entities.");
			} else {
				foreach ($actions as $action) {
					if (!in_array($action, $this->allEntityActions[$entity])) {
						$this->addErrorMessage("The entity action `{$entity}-{$action}` is not valid for auto-queue entities.");
					}
				}
			}
		}

		// check URL
		$url = $this->itemsList['url'];
		if ($url!==null and !$url and $this->itemsList['enabled']) {
			$this->addErrorMessage("The URL is mandatory.");
		} elseif ($url and !\Engine\Validator::set($url)->isUrl()) {
			$this->addErrorMessage("The URL is not valid.");
		}

		// chweck username and password
		$username = $this->itemsList['username'];
		$password = $this->itemsList['password'];
		if ($password and !$username) {
			$this->addErrorMessage("You must set the username if you want to set a password.");
		}

	}

	public function setActiveEntityActions(array $entityActions)
	{
		if (!$entityActions) {
			$this->delete('activeEntityActions');
		} else {
			$saveActions = [];
			foreach ($entityActions as $ent=>$actions) {
				$saveActions[$ent] = array_values($actions);
			}
			$this->set('activeEntityActions', serialize($saveActions));
		}

	}

	public function getActiveEntityActions()
	{
		$activeActions = $this->get('activeEntityActions');
		return $activeActions ? unserialize($activeActions) : [];
	}


	public function setAutoQueueEntityActions(array $entityActions)
	{
		if (!$entityActions) {
			$this->delete('autoQueueEntityActions');
		} else {
			$saveActions = [];
			foreach ($entityActions as $ent=>$actions) {
				$saveActions[$ent] = array_values($actions);
			}
			$this->set('autoQueueEntityActions', serialize($saveActions));
		}
	}

	public function getAutoQueueEntityActions()
	{
		$activeActions = $this->get('autoQueueEntityActions');
		return $activeActions ? unserialize($activeActions) : [] ;
	}


	/**
	 * Indicates if a certain entity+action is active.
	 * @param string $entity
	 * @param string $action
	 * @return boolean
	 */
	public function getActiveEntityAction(string $entity, string $action)
	{
		$cfg = $this->getActiveEntityActions();
		if (!array_key_exists($entity, $cfg)) {
			return null;
		}

		return ($cfg[$entity] and in_array($action, $cfg[$entity])) ;
	}


	/**
	 * Indicates if a certain entity+action is supposed to be auto-queued.
	 * @param string $entity
	 * @param string $action
	 * @return NULL|boolean
	 */
	public function getAutoQueueEntityAction(string $entity, string $action)
	{
		$cfg = $this->getAutoQueueEntityActions();
		if (!array_key_exists($entity, $cfg)) {
			return null;
		}

		return ($cfg[$entity] and in_array($action, $cfg[$entity])) ;
	}

}