<?php
namespace SabaiApps\Directories\Component\Field\Renderer;

use SabaiApps\Directories\Component\Entity;
use SabaiApps\Directories\Component\Field\IField;

abstract class AbstractFileRenderer extends AbstractRenderer {

	protected $_fieldTypes;

	protected function _fieldRendererInfo() {
		return array(
			'field_types'      => $this->_fieldTypes,
			'default_settings' => array(
				'_separator' => ' ',
			),
			'inlineable'       => true,
		);
	}

	protected function _fieldRendererRenderField( IField $field, array &$settings, Entity\Type\IEntity $entity, array $values, ?array $context = null, $more = 0 ) {
		$ret = array();
		foreach ( $values as $value ) {
			$extension = $this->_getFileExtension( $field, $settings, $value, $entity );
			if ( ! $rendered = $this->_application->Filter( 'field_render_file', '', array( $field, $settings, $value, $entity, $extension ) ) ) {
				$rendered = $this->_renderFile( $field, $settings, $value, $entity, $extension );
			}
			$ret[] = $rendered;
		}
		return implode( $settings['_separator'], $ret );
	}

	protected function _renderFile( IField $field, array $settings, $value, Entity\Type\IEntity $entity, $extension ) {
		$rendered = $this->_getFileLink( $field, $settings, $value, $entity );
		if ( $icon = $this->_getFileIcon( $extension ) ) {
			$rendered = '<i class="' . $icon . '"></i> ' . $rendered;
		}
		return $rendered;
	}

	protected function _getFileIcon( $extension ) {
		switch ( $extension ) {
			case 'gif':
			case 'jpg':
			case 'jpeg':
			case 'png':
			case 'webp':
			case 'svg':
			case 'avif':
				return 'far fa-file-image';
			case 'xls':
				return 'far fa-file-excel';
			case 'php':
			case 'js':
			case 'html':
			case 'htm':
			case 'xml':
				return 'far fa-file-code';
			case 'zip':
			case 'tgz':
				return 'far fa-file-archive';
			case 'txt':
				return 'far fa-file-alt';
			case 'wmv':
			case 'mpg':
			case 'mpeg':
				return 'far fa-file-video';
			case 'mp3':
				return 'far fa-file-audio';
			case 'pdf':
				return 'far fa-file-pdf';
			case 'doc':
				return 'far fa-file-word';
			case 'ppt':
				return 'far fa-file-powerpoint';
			default:
				return 'far fa-file';
		}
	}

	abstract protected function _getFileExtension( IField $field, array $settings, $value, Entity\Type\IEntity $entity );
	abstract protected function _getFileLink( IField $field, array $settings, $value, Entity\Type\IEntity $entity );
}
