<?php

namespace Franzz\Spot;
use Franzz\Objects\UploadHandler;
use Franzz\Objects\Translator;

class Uploader extends UploadHandler
{
	private Media $oMedia;
	private Translator $oLang;

	public string $sBody;

	function __construct(Media &$oMedia, Translator &$oLang)
	{
		$this->oMedia = &$oMedia;
		$this->oLang = &$oLang;
		$this->sBody = '';

		parent::__construct(array(
			'upload_dir'		=> Media::MEDIA_FOLDER.'/',
			'image_versions'	=> array(),
			'accept_file_types'	=> '/\.(gif|jpe?g|png|mov|mp4)$/i'
		));
	}

	protected function validate($uploaded_file, $file, $error, $index, $content_range) {
		$bResult = parent::validate($uploaded_file, $file, $error, $index, $content_range);

		//Check project mode
		if(!$this->oMedia->isProjectEditable()) {
			$file->error = $this->get_error_message('upload.mode_archived', array($this->oMedia->getProjectCodeName()));
			$bResult = false;
		}

		return $bResult;
	}

	protected function handle_file_upload($uploaded_file, $name, $size, $type, $error, $index = null, $content_range = null) {
		$sExt = strtolower(pathinfo((string) $name, PATHINFO_EXTENSION));
		$sStoredName = bin2hex(random_bytes(16)).($sExt !== ''?'.'.$sExt:'');
		$file = parent::handle_file_upload($uploaded_file, $sStoredName, $size, $type, $error, $index, $content_range);

		if(empty($file->error)) {
			$asResult = $this->oMedia->addMedia($file->name);
			if(!$asResult['result']) $file->error = $this->get_error_message($asResult['desc'], $asResult['data']);
			else {
				$file->original_name = basename((string) $name);
				$file->id = $this->oMedia->getMediaId();
				$file->thumbnail = $asResult['data']['thumb_path'];
			}
		}

		return $file;
	}

	protected function body($sBodyPart) {
		$this->sBody .= $sBodyPart;
	}

	protected function get_error_message($sError, $asParams=array()) {
		$sTranslatedError = $this->oLang->getTranslation($sError, $asParams);
		if($sTranslatedError) return $sTranslatedError;
		elseif(array_key_exists($sError, $this->error_messages)) return $this->error_messages[$sError];
		else return $sError;
	}
}
