<?php

// TODO: se pare ca nu e folosita nicaieri clasa asta, nici in parser nu exista; daca pica, trage probabil si countruy dupa el

namespace App\ImportedDocument;

/**
 * Stores a city details for an imported document.
 * @author Gabriel
 */
class City extends EntityAbstract
{

	/**
	 * The country object.
	 * @var \App\ImportedDocument\Country
	 */
	protected $country;

	/**
	 * The city id in TINA.
	 * @var Int
	 */
	public $idTina;

	/**
	 * The city id in the ext system.
	 * @var String
	 */
	public $idSystem;

	/**
	 * The city ISO code3.
	 * @var String
	 */
	public $code3;

	/**
	 * The city name.
	 * @var String
	 */
	public $name;


	/**
	 * Sets the country object.
	 * @param \App\ImportedDocument\Country $country
	 */
	public function setCountry(Country $country)
	{
		$this->country = $country;
	}

	/**
	 * Returns the country object.
	 * @return \App\ImportedDocument\Country
	 */
	public function getCountry()
	{
		return $this->country;
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\ImportedDocument\EntityAbstract::validateEntityFields()
	 */
	protected function validateEntityFields(\App\MessagesCollector $messagesCollector)
	{

		if (!$this->country) {
			$messagesCollector->addInfo('The city does not contain country details.');
		}

		if ( $this->idTina and (!is_numeric($this->idTina) or $this->idTina<0) ) {
			$messagesCollector->addInfo('The TINA id is invalid - it should be a positive integer.');
		}

		if ( $this->code3 and (mb_strlen($this->code3)!=3) ) {
			$messagesCollector->addInfo('The code3 should have exactly 3 chars.');
		}

		if (!$this->idTina and !$this->idSystem and !$this->code3 and !$this->name) {
			$messagesCollector->addInfo('The city does not contain any details for matching.');
		}

		// append country validators
		if ($this->country) {
			$this->country->validateEntityFields($messagesCollector);
		}

	}

	/**
	 * (non-PHPdoc)
	 *
	 */
	public function getMatchedId($idExternalSystem)
	{

		$matchObj = new \App\ImportedDocument\EntityMatch\City('intersect');
		if ($this->idTina) {
			$matchObj->setId($this->idTina);
		}
		if ($idExternalSystem and $this->idSystem) {
			$matchObj->setIdInExtSys($this->idSystem, $idExternalSystem);
		}
		if ($this->code3) {
			$matchObj->setCode3($this->code3);
		}
		if ($this->name) {
			$matchObj->setName($this->name, true);
		}
		// filter by country code
		if ($this->country) {
			$countryCode = $this->country->getMatchedId();
			if ($countryCode) {
				$matchObj->filterByCountryCode($countryCode);
			}
		}

		$matchObj->search();
		if ($matchObj->getResultsCount()==1) {
			return $matchObj->getFirstMatchId();
		}

		return 0;

	}

}
