<?php
namespace App\ImportedDocument;

/**
 * Stores imported service details for imported document.
 * @author cristiana.matache
 */

class ImportedService extends EntityAbstract
{

	/**
	 * The service id from TINA
	 * @var Int
	 */
	public $idTina;

	/**
	 * The service id from the external system
	 * @var String
	 */
	public $idServiceExtSys;

	/**
	 * The external system code
	 * @var String
	 */
	public $extSysCode;

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\ImportedDocument\EntityAbstract::validateEntityFields()
	 */
	protected function validateEntityFields(\App\MessagesCollector $messagesCollector)
	{
		if ($this->idTina and !is_numeric($this->idTina) and $this->idTina<0) {
			$messagesCollector->addWarning('The TINA id must be numeric.');
		}

		if ($this->extSysCode and !\Entity\ExtResSystem::getSystemIdByCode($this->extSysCode)) {
			$messagesCollector->addError('The external system code is not valid.');
		}
	}


	/**
	 * Tries to correctly match the imported service id (from TINA) depending on the service inputs.
	 * It returns a imported service id (id from TINA).
	 */
	public function getMatchedId()
	{

		// check/match the imported service
		$idImportedServMatched = 0;
		if ($this->extSysCode and $this->idServiceExtSys) {
			$idSystemMatched = \Entity\ExtResSystem::getSystemIdByCode($this->extSysCode);

			// check if the system is matched
			if ($idSystemMatched) {
				$result = \Entity\ImportedService::getDetailsByServiceExtSys($this->idServiceExtSys, $idSystemMatched, false);
				$idImportedServMatched = $result['id'];
			}

		}

		// if nothing matched by imported service (ext id) we consider TINA id
		if (!$idImportedServMatched) {
			$return = (Int)$this->idTina;
		}
		// if something matched by imported service (ext id)
		else {
			// check it against TINA id
			if (!$this->idTina or $this->idTina==$idImportedServMatched) {
				$return = $idImportedServMatched;
			} else {
				$return = 0;
			}
		}

		// if, in the end, no service found - return 0
		return $return;

	}


}