<?php

namespace Velis\Bpm\Ticket\Mixin;

use Velis\App;
use Velis\Bpm\Ticket\Post\File;
use Velis\DuplicateRequestException;
use Velis\Exception;
use Velis\Mvc\Controller\AbstractRestController;

trait FilesDataTrait
{
    /**
     * Returns true if files exist in request
     * @return bool
     */
    protected function _filesExist()
    {
        if ($this instanceof AbstractRestController) {
            $filter = $this->params;
        } else {
            $filter = $this->_filter;
        }

        return (is_array($_FILES['postFiles']['name']) && array_filter($_FILES['postFiles']['name']))
            || (!is_array($_FILES['postFiles']['name']) && strlen($_FILES['postFiles']['name']))
            || is_array($filter['fileHash'])
            || is_array($filter['emailAttachments'])
            || is_array($filter['ticketFiles']);
    }

    /**
     * Returns uploaded files data
     * @return array
     * @throws DuplicateRequestException
     */
    protected function _getFilesData()
    {
        if ($this instanceof AbstractRestController) {
            $filter = $this->params;
        } else {
            $filter = $this->_filter;
        }

        if (!$this->_filesExist()) {
            return [];
        }

        $filesData = [];

        if (is_array($_FILES['postFiles']['name']) && array_filter($_FILES['postFiles']['name'])) {
            foreach ($_FILES['postFiles']['name'] as $key => $fileName) {
                if (strlen($fileName)) {
                    $filesData[] = [
                        'name'     => $fileName,
                        'type'     => $_FILES['postFiles']['type'][$key],
                        'tmp_name' => $_FILES['postFiles']['tmp_name'][$key],
                        'error'    => $_FILES['postFiles']['error'][$key],
                        'size'     => $_FILES['postFiles']['size'][$key],
                    ];
                }
            }
        }

        if (!is_array($filter['fileHash'])) {
            return $filesData;
        }

        foreach ($filter['fileHash'] as $hash => $fileName) {
            if (!strlen($fileName)) {
                continue;
            }

            /** @var FilesystemInterface $filesystem */
            $filesystem = App::$di->get('filesystem');

            $filePath = sprintf('temp/%s', $hash);
            $recentHashes = App::$session->get(File::RECENT_HASHES_SESSION_KEY) ?: [];
            if (!$filesystem->has($filePath) && in_array($filePath, $recentHashes)) {
                throw new DuplicateRequestException();
            }

            $fileData = [
                'name' => $fileName,
                'type' => File::getMimeType($filePath, $fileName),
                'tmp_name' => $filePath,
                'error' => 0,
                'size' => $filesystem->size($filePath),
            ];

            if (File::isSupportedImageType($fileData['type'])) {
                try {
                    $imageSizeArr = $filesystem->getImageSize($filePath);

                    $fileData['width'] = $imageSizeArr[0];
                    $fileData['height'] = $imageSizeArr[1];
                } catch (Exception $e) {
                    // do nothing - some image formats are not supported, e.g. HEIC
                }
            }

            $filesData[] = $fileData;
        }

        return $filesData;
    }
}
