<?php
namespace ALPCAL\Draw;

/**
 * Class to draw alpineCalendar events.
 
 Requires:
 	getData(); // retrieves data and puts in in object
 */

use DateTime, DateInterval, Exception;
use ALPCAL\Util\CacheFileRenamer;
use ALPCAL\Storage\CacheFiles;
use ALPCAL\Remote\AlpineCalendar_ca;

Class Event extends \ALPCAL\Defaults
{
	public $id;
	public $event; // holder for the event
	public $error = false;	// error handler
	
	
	public function __construct($alpcal_options)
	{
		parent::__construct($alpcal_options); // put the construct items in place

  	}
	
	public function setId($id)
	{
		$id = (int) $id;
		if (!is_numeric($id)) { throw new Exception("Event ID must be numeric."); }
		if ($id<1) { throw new Exception("Event ID invalid."); }
		$this->id = $id;
	}

	/**
	 * called to initiate the fetching of data
	 */
	public function getData()
	{
		if (!$this->id) { throw new Exception("Draw\Event requires that Id be set."); }

		// create an object for dealing with file storage
		$this->cacheFiles = new CacheFiles($this->alpcal_options['cache_folder']); 
		$this->cacheFiles->setFileName($this->id);
		$this->cacheFiles->setFileFolder("Events");
		$this->cacheFiles->getFile();
		
		// if the file is older than allowed in cache, go fetch it
		if ($this->cacheFiles->fileAge > $this->alpcal_options['cache_length_events'])
			{
			try {
				echo "cache too old";
				$this->fetchRemoteEventData(); // go get the data for the draw range
 				$this->cacheFiles->writeFile($this);
				}
			catch(Exception $e)
				{
				echo "cache valid 2.";
				$this->setEventFromCache();
				}
			}
		else{
			echo "cache valid 1.";
			$this->setEventFromCache();
			}
	}

	
	/**
	 * Fetches remote data from source
	 */
	public function fetchRemoteEventData()
	{	
		$evClass = new AlpineCalendar_ca($this->alpcal_options);
		$this->event = $evClass->returnEvent($this->id);

	}
	
	
	public function setEventFromCache()
	{
		$decodedObj = json_decode($this->cacheFiles->returnFileLiteral());
		$this->event = $decodedObj->event;
		
	}

}