<?php
namespace Modules\Documents\Generate\Email\EmailList;

class Model extends \App\Mvc\Model_ListingAbstract
{
	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Model_ListingAbstract::list_execute()
	 */
	public function list_execute(\App\Mvc\View\Listing\Members\Params $listingParams)
	{

		// get listing filters
		$filters = $listingParams->getFilters();

		$idDocument = $filters['idDocument'];
		$documentEntity = \Entity\Document::select($idDocument);

		$emailsList = [];
		$path = APP_REAL_PATH.$this->globalCfg['paths']['uploadedDocumentsEmail'];
		foreach ($documentEntity->history as $key => $records) {
			if ($records['op'] == 'e') {
				if ($records['details']['uplDocs']) {
					foreach ($records['details']['uplDocs'] as $diskFileName => $fileName) {
						$fileExists = true;
						if (!\Engine\File::check($path.$diskFileName)) {
							$fileExists = false;
						}

						$records['details']['uplDocs'][$diskFileName] = [
							'fileName' => 	$fileName,
							'fileExists' =>	$fileExists,
						];
					}
				}

				$emailsList[$key] = [
					'key' =>					$key,
					'idDocument' =>				$idDocument,
					'sender' => 				$records['us'],
					'sendTime'=>				$records['t'],
					'to' => 					$records['details']['to'],
					'cc' => 					$records['details']['cc'],
					'bcc' => 					$records['details']['bcc'],
					'readReceipt' => 			$records['details']['readReceipt'],
					'genDocs' => 				$records['details']['genDocs'],
					'uplDocs' => 				$records['details']['uplDocs'],
					'subject' => 				$records['details']['subject'],
					'body' => 					$records['details']['body'],
				];
			}
		}

		$total = count($emailsList);

		$emailsList = array_slice($emailsList, $listingParams->getResultsPerPage()*$listingParams->getCurrentPage(), $listingParams->getResultsPerPage(), false);

		$this->recordsList = $emailsList;
		$this->totalRecordsCount = 	$total;

	}

	/**
	 * Get file content
	 * @param String $idDocument
	 * @param String $idFile
	 * @throws \Engine\Mvc\ModelException
	 */
	public function getFileContent($idDocument, $idFile)
	{
		$uploadedDocs = $this->getUploadedDocuments($idDocument);

		// check if fileId is correct
		if (!array_key_exists($idFile, $uploadedDocs)) {
			throw new \Engine\Mvc\ModelException(sprintf("File with id (%s) is not available for this document", $idFile));
		}

		// check if file exists on disk
		$path = APP_REAL_PATH.$this->globalCfg['paths']['uploadedDocumentsEmail'];
		if (!\Engine\File::check($path.$idFile)) {
			throw new \Engine\Mvc\ModelException(sprintf("File %s doesn't exist on disk", $uploadedDocs[$idFile]));
		}

		return \Engine\File::getContents($path.$idFile);

	}

	private function getUploadedDocuments($idDocument)
	{
		// check entity id
		$document = \Entity\Document::select($idDocument);

		if (!$document->recordExists()) {
			throw new \Engine\Mvc\ModelException(sprintf("Document with id %s not exist", $idDocument));
		}

		// get uploaded documents
		$uploadedDocs = [];
		foreach ($document->history as $record) {
			if ($record['op'] == 'e') {
				if ($record['details']['uplDocs']) {
					foreach ($record['details']['uplDocs'] as $fileDiskName => $fileName) {
						$uploadedDocs[$fileDiskName] = $fileName;
					}
				}
			}
		}

		return $uploadedDocs;
	}

	public function getFileName($idDocument, $idFile)
	{
		$uploadedDocs = $this->getUploadedDocuments($idDocument);

		// check if fileId is correct
		if (!array_key_exists($idFile, $uploadedDocs)) {
			throw new \Engine\Mvc\ModelException(sprintf("File with id (%s) is not available for this document", $idFile));
		}

		return $uploadedDocs[$idFile];
	}
}