<?php

namespace idoit\Module\CustomFields\Controller;

use isys_application;
use isys_helper_textformat;
use isys_module_custom_fields;
use SplFileInfo;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class ChangeIconController
{
    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function modal(Request $request): JsonResponse
    {
        try {
            $template = isys_application::instance()->container->get('template');

            $template
                ->activate_editmode()
                ->assign('uploadConditions', $this->fetchUploadConditions())
                ->assign('categoryIcons', $this->collectIcons())
                ->assign('defaultIcon', isys_module_custom_fields::DEFAULT_CATEGORY_ICON);

            return new JsonResponse([
                'success' => true,
                'message' => '',
                'data'    => $template->fetch(isys_module_custom_fields::getPath() . 'templates/popup/change-icon.tpl'),
            ]);
        } catch (\Exception $e) {
            return new JsonResponse([
                'success' => false,
                'message' => $e->getMessage(),
                'data'    => null,
            ]);
        }
    }

    /**
     * @return array
     * @throws \Exception
     */
    private function fetchUploadConditions(): array
    {
        $uploadType = isys_application::instance()->container->get('upload')->getUploadType('cmdb.object-type-icon');

        return [
            'sizeLimit' => ($uploadType->getSizeLimit() / 1024) . ' KB',
            'validExtensions' => isys_helper_textformat::this_this_and_that($uploadType->getValidExtensions()),
        ];
    }

    /**
     * @return array|array[]
     * @throws \Exception
     */
    private function collectIcons(): array
    {
        $tenantId = 0;
        $appDir = rtrim(isys_application::instance()->app_path, '/') . '/';
        $objectTypeIcons = ['old' => [], 'new' => [], 'custom' => []];
        $routeGenerator = isys_application::instance()->container->get('route_generator');

        if (isys_application::instance()->tenant !== null) {
            $tenantId = isys_application::instance()->tenant->id;
        }

        // Load very old object type icons.
        foreach (glob($appDir . 'images/icons/tree/*') as $iconPath) {
            $image = $this->getImage($iconPath);

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

            $objectTypeIcons['old'][str_replace($appDir, '', $iconPath)] = $image->getBasename();
        }

        // Load old object type icons.
        foreach (glob($appDir . 'images/icons/silk/*') as $iconPath) {
            $image = $this->getImage($iconPath);

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

            $objectTypeIcons['old'][str_replace($appDir, '', $iconPath)] = $image->getBasename();
        }

        // Load modern icons.
        foreach (glob($appDir . 'images/axialis/*/*.svg') as $iconPath) {
            $image = $this->getImage($iconPath);

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

            $objectTypeIcons['new'][str_replace($appDir, '', $iconPath)] = $image->getBasename();
        }

        // Load custom (user uploaded) icons.
        foreach (glob($appDir . "upload/images/{$tenantId}/object-type/icons/*") as $iconPath) {
            $image = $this->getImage($iconPath);

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

            $url = ltrim($routeGenerator->generate('cmdb.object-type.icon-name', ['filename' => $image->getBasename()]), '/');

            $objectTypeIcons['custom'][$url] = $image->getBasename();
        }

        asort($objectTypeIcons['old']);
        asort($objectTypeIcons['new']);
        asort($objectTypeIcons['custom']);

        return $objectTypeIcons;
    }

    /**
     * @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;
    }
}
