<?php
namespace ALPCAL\Storage;
/**
 * Storage handler for a Cached Files
 */
use ALPCAL\Storage\Folders as Folders_Storage;
use ALPCAL\Util\CacheFileRenamer as CFR;

Class CacheFiles
{
	protected $folders; // folders created by ALPCAL\Storage\Folders
	
	public $creationTime;
	public $fileName;
	public $fileFullName; // full name with path and .json extension
	public $fileFolder;
	public $fileTime; // time the file was created
	public $fileAge = 999999; // default long age in case of null
//	public $fileLiteral; // caused recursive cache size increase

	public function __construct($rootFolder)
	{
		if (!$rootFolder) { throw new \Exception("Called Storage/CacheFiles without setting root."); }
		$this->folders = new Folders_Storage($rootFolder);
		$this->creationTime = time();
  	}
	
	public function setFileFolder($f)
	{
		if (!array_key_exists($f,$this->folders->cacheDirs)) { throw new \Exception("Util\CacheFiles did not find passed folder ({$f})."); }
		$this->fileFolder = $f;
	}
	
	public function setFileName($nm)
	{
		$cfr = new CFR; // create a new file renamer class
		$nm = $cfr->convertFromUrl($nm);
		$this->fileName = $nm;
	}
	
	/**
	 * gets the file information 
	 */
	public function getFile()
	{
		if (!$this->fileName) { throw new \Exception("Util\CacheFile could not run getFile - no fileName."); }
		if (!$this->fileFolder) { throw new \Exception("Util\CacheFile could not run getFile - no fileFolder."); }
		$this->fileFullName = $this->folders->cacheDirs[$this->fileFolder].$this->fileName.'.json';
		if (file_exists($this->fileFullName))
		{
			$this->fileTime = filemtime($this->fileFullName);
			$this->fileAge = time() - $this->fileTime;
		}
	}
	
	public function returnFileLiteral()
	{
		if (!$this->fileFullName) { throw new \Exception("Util\CacheFile could not run getFileLiteral - no fileFullName."); }
		return file_get_contents($this->fileFullName);
	}

	public function writeFile($theFile)
	{
		$theFile->cacheFiles = null;
		$theFile = json_encode($theFile);
		unlink($theFile);
		file_put_contents($this->fileFullName,$theFile);
		return true;
	}
	
	public function testThis()
	{
		echo "<pre>";
		echo "<pre>";print_r($this);echo "</pre>";
//		print_r(parent::$this->workingMonth); argh
		echo "</pre>";
	}


}
