<?php
namespace App\GenDocument\PivotCalendarEvent;
/**
 * Populate the ics calendar object based on service entity
 * @author FlorinRusu
 *
 */
class Service
{

	/**
	 * Stores the calendar object
	 * @var \App\Utils\Calendar\Calendar
	 */
	protected $calendarObject = NULL;

	/**
	 * Stores the service entity
	 * @var \Entity\Service
	 */
	protected $serviceEntity = NULL;


	/**
	 *
	 * @param \App\Utils\Calendar\Calendar $calendarObject
	 * @param \Entity\Service $serviceEntity
	 */
	public function __construct(\App\Utils\Calendar\Calendar $calendarObject, \Entity\Service $serviceEntity)
	{
		$this->calendarObject = $calendarObject;
		$this->serviceEntity = $serviceEntity;
	}

	/**
	 * Populate the event from service entity (one event, which is ALLDAY, per service)
	 * Populate the description of the event with the details of the trip
	 */
	public function populate()
	{
		$chosenOfferEnt = $this->serviceEntity->chosenOffer;

		if (!$chosenOfferEnt->recordExists()) {
			return false;
		}

		$itinerarySegments = $chosenOfferEnt->itinerary->getSegments();
		if ($itinerarySegments) {
			foreach ($itinerarySegments as $segment) {
				$eventObjectWithItinerary = new \App\Utils\Calendar\Event();

				$this->populateEventItinerarySegment($segment, $eventObjectWithItinerary);
				$this->calendarObject->addEvent($eventObjectWithItinerary);
			}
		}
		else {
			$eventObjectWithoutItinerary = new \App\Utils\Calendar\Event();

			$this->populateAllDayEvent($eventObjectWithoutItinerary);
			$this->calendarObject->addEvent($eventObjectWithoutItinerary);
		}
	}


	/**
	 * Populate event for a single segment from an itinerary
	 * @param \App\ItinerarySegment $segment
	 * @param \App\Utils\Calendar\Event $event
	 */
	private function populateEventItinerarySegment(\App\ItinerarySegment $segment, \App\Utils\Calendar\Event $event)
	{

		$departureStationTimezone = '';
		$arrivalStationTimezone = '';
		if ($segment->getDepartureStation()->recordExists() and $segment->getArrivalStation()->recordExists()) {
			$departureStationTimezone = new \DateTimeZone(\Entity\Station::select($segment->getDepartureStation()->getId())->timezone);
			$arrivalStationTimezone = new \DateTimeZone(\Entity\Station::select($segment->getArrivalStation()->getId())->timezone);
		}

		if ($segment->getDepartureDateTime() and $segment->getArrivalDateTime() and $departureStationTimezone and $arrivalStationTimezone) {
			$event->setAllDay(false);

			$departureDateTime = $segment->getDepartureDateTime()->setTimezone($departureStationTimezone);
			$arrivalDateTime = $segment->getArrivalDateTime()->setTimezone($arrivalStationTimezone);
		}
		else {
			$event->setAllDay(true);

			$departureDateTime = $this->serviceEntity->chosenOffer->startDatetime;
			$arrivalDateTime = $this->serviceEntity->chosenOffer->endDatetime;

			if ($arrivalDateTime->isEmpty()) {
				$arrivalDateTime = $departureDateTime;
			}
		}

		//////////// POPULATE EVENT START DATE ////////////////////////////////////////////////////
		$event->setDtStart($departureDateTime);

		/////////// POPUlATE EVENT END DATE ///////////////////////////////////////////////////////
		$event->setDtEnd($arrivalDateTime);

		/////////// POPUlATE EVENT SUMMARY ////////////////////////////////////////////////////////
		$summary = $this->populateSummaryItinerarySegment($segment);
		$event->setSummary($summary);

		/////////// POPUlATE EVENT DESCRIPTION ////////////////////////////////////////////////////
		$description = $this->populateDescriptionItinerarySegment($segment);
		$event->setDescription($description);
	}

	/**
	 * Populate all day event (any service that doesn't have itinerary)
	 * @param \App\Utils\Calendar\Event $event
	 */
	private function populateAllDayEvent(\App\Utils\Calendar\Event $event)
	{

		$event->setAllDay(true);

		$departureDateTime = $this->serviceEntity->chosenOffer->startDatetime;
		$destinationDateTime = $this->serviceEntity->chosenOffer->endDatetime;

		if ($destinationDateTime->isEmpty()) {
			$destinationDateTime = $departureDateTime;
		}

		//////////// POPULATE EVENT START DATE ////////////////////////////////////////////////////
		$event->setDtStart($departureDateTime);

		/////////// POPUlATE EVENT END DATE ///////////////////////////////////////////////////////
		$event->setDtEnd($destinationDateTime);

		/////////// POPUlATE EVENT SUMMARY ////////////////////////////////////////////////////////
		$summary = $this->populateSummaryAllDayEvent();
		$event->setSummary($summary);

		/////////// POPUlATE EVENT DESCRIPTION ////////////////////////////////////////////////////
		$description = $this->populateDescriptionAllDayEvent();
		$event->setDescription($description);
	}

	/**
	 * Generate a short summary (calendar title) for itinerary segment
	 * @param \App\ItinerarySegment $segment
	 * @return string
	 */
	private function populateSummaryItinerarySegment(\App\ItinerarySegment $segment)
	{

		$summary = '';
		if ($segment->getSupplier()->codeIata and $segment->getTransportNumber()) {
			$summary .= $segment->getSupplier()->codeIata."-".$segment->getTransportNumber().' ';
		}

		$cities = [];

		if ($segment->getDepartureCity()->name) {
			$cities[$segment->getDepartureCity()->name] = true;
		}

		if ($segment->getArrivalCity()->name) {
			$cities[$segment->getArrivalCity()->name] = true;
		}

		if(count($cities)) {
			$summary .= $this->serviceEntity->serviceName.' ('.implode('-', array_keys($cities)).")";
		}
		else {
			$summary .= $this->serviceEntity->serviceName.' - '.\Engine\DateTime::isoToStd($segment->getDepartureDateTime()->formatDatetimeIso());
		}

		return $summary;
	}

	/**
	 * Generate a short summary (calendar title) for all day events
	 * @param \App\ItinerarySegment $segment
	 * @return string
	 */
	private function populateSummaryAllDayEvent()
	{
		$chosenOfferEnt = $this->serviceEntity->chosenOffer;
		$summary = '';

		if ($chosenOfferEnt->confirmationNumber) {
			$summary .= "[{$chosenOfferEnt->confirmationNumber}] ";
		}

		$summary .= $this->serviceEntity->serviceName;

		if ($this->serviceEntity->chosenOffer->departureCity->recordExists() and $this->serviceEntity->chosenOffer->destinationCity->recordExists()) {
			$summary .= " (".$this->serviceEntity->chosenOffer->departureCity->name."-".$this->serviceEntity->chosenOffer->destinationCity->name.")";
		}
		elseif ($this->serviceEntity->chosenOffer->departureCity->recordExists() and !$this->serviceEntity->chosenOffer->destinationCity->recordExists()) {
			$summary .= " (".$this->serviceEntity->chosenOffer->departureCity->name.")";
		}

		return $summary;
	}

	/**
	 * Generate description for itinerary segment
	 * @param \App\ItinerarySegment $segment
	 * @return string
	 */
	private function populateDescriptionItinerarySegment(\App\ItinerarySegment $segment)
	{
		$loaderLang = \App\Loader_Lang::getInstance()->loadAppFile("_customLoad/pivotCalendarEvent/service.lang.php");;
		$_LANG = $loaderLang->getGlobal();

		$descriptionHtml = "";

		$descriptionHtml .= sprintf("<div><b>%s:</b> ", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['passengers']);
		$i = 1;
		foreach ($this->serviceEntity->idCustomersList as $idCustomer) {
			$customerEnt = \Entity\Customer::select($idCustomer);

			if (count($this->serviceEntity->idCustomersList)!=$i) {
				$descriptionHtml .= $customerEnt->titleName." ".$customerEnt->nameStandard.", ";
			} else {
				$descriptionHtml .= $customerEnt->titleName." ".$customerEnt->nameStandard;
			}
			$i++;
		}

		$descriptionHtml .= "</div>";
		$descriptionHtml .= sprintf("<div><b>%s:</b> ", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['flightDetails']);

		if ($segment->getDepartureDateTime() and $segment->getArrivalDateTime()) {
			$descriptionHtml .= $segment->getDepartureDateTime()->formatDateStd();

			if ($segment->getDepartureDateTime()->format('H:i:s') != "00:00:00") {
				$descriptionHtml .= " ".$segment->getDepartureDateTime()->format('H:i:s');
			}

			$descriptionHtml .= " - ".$segment->getArrivalDateTime()->formatDateStd();

			if ($segment->getArrivalDateTime()->format('H:i:s') != "00:00:00") {
				$descriptionHtml .= " ".$segment->getArrivalDateTime()->format('H:i:s');
			}
		}

		if ($segment->getDuration()) {
			$descriptionHtml .= sprintf(" (%s: %s)", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['duration'],$segment->getDuration());
		}

		if ($segment->getSupplier()->codeIata and $segment->getTransportNumber()) {
			$descriptionHtml .= " / ".$segment->getSupplier()->codeIata."-".$segment->getTransportNumber();
		}

		if ($segment->supplierRecordLocator) {
			$descriptionHtml .= " / ".$segment->supplierRecordLocator;
		}

		$descriptionHtml .= "</div>";
		$descriptionHtml .= sprintf("<div><b>%s:</b> ", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['departureDetails']);
		if ($segment->getDepartureCountry()->name) {
			$descriptionHtml .= $segment->getDepartureCountry()->name;
		}
		if ($segment->getDepartureCity()->name) {
			$descriptionHtml .= " - ".$segment->getDepartureCity()->name;
		}
		if ($segment->getDepartureStation()->name) {
			$descriptionHtml .= " - ".$segment->getDepartureStation()->name;
		}
		if ($segment->getTerminalCheckIn()) {
			$descriptionHtml .= sprintf(" - %s: %s", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['terminal'], $segment->getTerminalCheckIn());
		}


		$descriptionHtml .= "</div>";
		$descriptionHtml .= sprintf("<div><b>%s:</b> ", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['arrivalDetails']);
		if ($segment->getArrivalCountry()->name) {
			$descriptionHtml .= $segment->getArrivalCountry()->name;
		}
		if ($segment->getArrivalCity()->name) {
			$descriptionHtml .= " - ".$segment->getArrivalCity()->name;
		}
		if ($segment->getArrivalStation()->name) {
			$descriptionHtml .= " - ".$segment->getArrivalStation()->name;
		}
		if ($segment->getTerminalCheckOut()) {
			$descriptionHtml .= sprintf(" - %s: %s", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['terminal'], $segment->getTerminalCheckOut());
		}

		$descriptionHtml .= "</div>";
		$descriptionHtml .= sprintf("<div>%s</div>", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['localTimes']);
		return $descriptionHtml;
	}

	/**
	 * Generate description for all day events
	 * @return string
	 */
	private function populateDescriptionAllDayEvent()
	{
		$loaderLang = \App\Loader_Lang::getInstance()->loadAppFile("_customLoad/pivotCalendarEvent/service.lang.php");;
		$_LANG = $loaderLang->getGlobal();

		$chosenOfferEnt = $this->serviceEntity->chosenOffer;

		$descriptionHtml = "";

		$descriptionHtml .= sprintf("<div><b>%s:</b> ", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['passengers']);
		$i = 1;
		foreach ($this->serviceEntity->idCustomersList as $idCustomer) {
			$customerEnt = \Entity\Customer::select($idCustomer);

			if (count($this->serviceEntity->idCustomersList)!=$i) {
				$descriptionHtml .= $customerEnt->titleName." ".$customerEnt->nameStandard.", ";
			} else {
				$descriptionHtml .= $customerEnt->titleName." ".$customerEnt->nameStandard;
			}
			$i++;
		}

		$descriptionHtml .= "</div>";
		$descriptionHtml .= sprintf("<div><b>%s:</b> ", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['details']);

		$startTime = $chosenOfferEnt->startDatetime->format('H:i:s');

		if ($chosenOfferEnt->startDatetime and $chosenOfferEnt->endDatetime) {

			$endTime = $chosenOfferEnt->endDatetime->format('H:i:s');

			$descriptionHtml .= $chosenOfferEnt->startDatetime->formatDateStd();
			if ($startTime != "00:00:00") {
				$descriptionHtml .= " ".$chosenOfferEnt->startDatetime->format('H:i:s');
			}


			$descriptionHtml .= " - ".$chosenOfferEnt->endDatetime->formatDateStd();
			if ($endTime != "00:00:00") {
				$descriptionHtml .= " ".$chosenOfferEnt->endDatetime->format('H:i:s');
			}
		}
		else {
			$descriptionHtml .= $chosenOfferEnt->startDatetime->formatDateStd();
			if ($startTime != "00:00:00") {
				$descriptionHtml .= " ".$chosenOfferEnt->startDatetime->format('H:i:s');
			}


			$descriptionHtml .= " - ".$chosenOfferEnt->startDatetime->formatDateStd();
			if ($startTime != "00:00:00") {
				$descriptionHtml .= " ".$chosenOfferEnt->startDatetime->format('H:i:s');
			}
		}

		if ($chosenOfferEnt->duration) {
			$descriptionHtml .= sprintf(" (%s: %s %s)", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['duration'], $chosenOfferEnt->duration, $chosenOfferEnt->durationType);
		}

		$descriptionHtml .= "</div>";
		$descriptionHtml .= sprintf("<div><b>%s:</b> ", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['productDetails']);

		if ($this->serviceEntity->productTypeReadable) {
			$descriptionHtml .= $this->serviceEntity->productTypeReadable;
		}

		if ($this->serviceEntity->multiplierReadable) {
			$descriptionHtml .= " - ".$this->serviceEntity->multiplierReadable;
		}

		if ($this->serviceEntity->supplierProduct->productName) {
			$descriptionHtml .= " - ".$this->serviceEntity->supplierProduct->productName;
		}

		if ($this->serviceEntity->supplierProduct->address) {
			$descriptionHtml .= " - ".$this->serviceEntity->supplierProduct->address;
		}

		if ($this->serviceEntity->supplierProduct->telephone) {
			$descriptionHtml .= " - ".$this->serviceEntity->supplierProduct->telephone;
		}

		$descriptionHtml .= "</div>";
		$descriptionHtml .= sprintf("<div>%s</div>", $_LANG['GenDocument']['PivotCalendarEvent']['Service']['localTimes']);
		return $descriptionHtml;
	}
}