<?php
namespace ALPCAL\Remote;
/**
 * AlpineCalendar.ca Remote fetch class
 
 Events must return from returnEvents() with minimum:
 EvID (guid for the event)
 EvTi (Title for the event to show on the web calendar)
 StDT (YYYY-MM-DD format)
 EnDT (YYYY-MM-DD format)
 
 */

Class AlpineCalendar_ca extends \ALPCAL\Models\Remote implements \ALPCAL\Interfaces\Remote
{
	public $buildUrl = "http://alpinecalendar.ca/api/?data=events&which_cal=[which_cal]&date_start=[date_start]&date_end=[date_end]";
	
	function __construct($alpcal_options)
	{
		$this->alpcal_options = $alpcal_options;
		$this->renderTime = time();
  	}
	
	/**
	 * Returns array of events in specified format
	 */
	public function returnEvents()
	{
		// build the URL
		if (!$this->stDt) { throw new \Exception("stDt not set in Remote\AlpineCalendar_ca"); }
		if (!$this->enDt) { throw new \Exception("enDt not set in Remote\AlpineCalendar_ca"); }
		$this->buildUrl = str_replace("[which_cal]",$this->alpcal_options['which_cal'],$this->buildUrl);
		$this->buildUrl = str_replace("[date_start]",$this->stDt->format('Y/m/d'),$this->buildUrl);
		$this->buildUrl = str_replace("[date_end]",$this->enDt->format('Y/m/d'),$this->buildUrl);
		
		try {
			// fetch via curl
			$GetRemoteFile = new \ALPCAL\Util\GetRemoteFile;
			$GetRemoteFile->set_url($this->buildUrl);
			$getEvents = $GetRemoteFile->get('curl');
			}
		catch(\Exception $e)
			{
			if ($e->getCode() == 22)
				{
				// there was an error thrown receiving
				die("Error: failed to retrieve file - ".$e->getMessage());
				}
			throw new \Exception($e->getMessage());
			}
		$eventsDecoded = json_decode($getEvents);
		
		foreach ($eventsDecoded as $k=>$ed)
		{
			$EvTi = '';
			if($ed->Location)
				{	$EvTi.= '<strong>'.$ed->Location.'</strong>: '; }
			if($ed->LocationAlt)
				{	$EvTi.= ' <strong>'.$ed->LocationAlt.'</strong>: '; }
			$EvTi.= ''.$ed->Title.''.'<br /><em>'.$ed->Overview.'</em>';
			$eventsDecoded[$k]->EvTi = $EvTi;
		}
		return $eventsDecoded;	
	}
	
	/**
	 * Returns single event data
	 */
	public function returnEvent($evId)
	{
		// build the URL
		$evId = (int) ($evId);
		if (!$evId) { throw new \Exception("evId not set in Remote\AlpineCalendar_ca::returnEvent"); }
		$url = 'http://alpinecalendar.ca/api/?data=event&id='.$evId;
		try {
			// fetch via curl
			$GetRemoteFile = new \ALPCAL\Util\GetRemoteFile;
			$GetRemoteFile->set_url($url);
			$getEvent = $GetRemoteFile->get('curl');
			}
		catch(\Exception $e)
			{
			if ($e->getCode() == 22)
				{
				// there was an error thrown receiving
				die("Error: failed to retrieve file - ".$e->getMessage());
				}
			throw new \Exception($e->getMessage());
			}
		$eventDecoded = json_decode($getEvent);
		return $eventDecoded;
	}
	
	
//	/**
//	 * Returns array of categories in specified format -- DECIDED TO MAKE THIS ITS OWN REMOTE, BUT WILL LEAVE THIS HERE FOR FUTURE THOUGHTS
//	 */
//	public function returnCategories($inSpecifiedDateRange=false)
//	{
//		
//	}
	
}
