<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Controller;

use idoit\Module\Cmdb\Controller\ImageController;
use idoit\Module\SyneticsFlows\Auth;
use idoit\Module\SyneticsFlows\Controller\Response\ArrayResponse;
use idoit\Module\SyneticsFlows\Model\Dto\IdoitImage;
use isys_application;
use isys_auth;
use SplFileInfo;
use Symfony\Component\HttpFoundation\Response;

class IdoitImageController
{
    private string $appDir;

    public function __construct()
    {
        $this->appDir = rtrim(isys_application::instance()->app_path, '/') . '/';
    }

    /**
     * @return Response
     * @throws \Exception
     */
    public function find(): Response
    {
        if (!Auth::instance()->manageFlows(isys_auth::VIEW)) {
            return JSONResponseFactory::accessDenied();
        }
        $result = [];
        $tenantId = isys_application::instance()->tenant?->id ?? 0;
        $icons = [
            'icon' => [
                'images/icons/tree/*',
                'images/icons/silk/*',
                'images/axialis/*/*.svg',
            ],
            'custom' => [
                "upload/images/{$tenantId}/object-type/icons/*",
            ]
        ];

        foreach ($icons as $type => $sources) {
            foreach ($sources as $path) {
                foreach (glob($this->appDir . $path) as $imagePath) {
                    $image = $this->getImage($imagePath);

                    if ($image === null) {
                        continue;
                    }

                    $result[] = new IdoitImage(
                        $this->getImageUrl($type, $imagePath, $image->getBasename()),
                        $image->getBasename()
                    );
                }
            }
        }

        $additionalObjectTypeImages = ImageController::getAdditionalObjectTypeImagePaths('');
        foreach ($additionalObjectTypeImages as $path) {
            foreach (glob($this->appDir . $path . '/*') as $imagePath) {
                $image = $this->getImage($imagePath);

                if ($image === null) {
                    continue;
                }

                $result[] = new IdoitImage(
                    $this->getImageUrl('custom', $imagePath, $image->getBasename()),
                    $image->getBasename(),
                );
            }
        }

        return new ArrayResponse($result, count($result));
    }

    /**
     * @param string $type
     * @param string $imagePath
     * @param string $fileName
     * @return string
     * @throws \Exception
     */
    private function getImageUrl(string $type, string $imagePath, string $fileName): string
    {
        if ($type === 'icon') {
            return str_replace($this->appDir, '', $imagePath);
        }

        return isys_application::instance()
            ->container->get('route_generator')
            ->generate('cmdb.object-type.icon-name', ['filename' => $fileName]);
    }

    /**
     * @param string $imagePath
     * @return SplFileInfo|null
     */
    private function getImage(string $imagePath): ?SplFileInfo
    {
        $imageFile = new SplFileInfo($imagePath);

        if (!in_array($imageFile->getExtension(), isys_application::ALLOWED_IMAGE_EXTENSIONS, true)) {
            return null;
        }

        return $imageFile;
    }
}