<?php

namespace YOOtheme\Theme\Joomla;

use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\User\User;
use YOOtheme\ConfigObject;
use YOOtheme\Joomla\Media;

class FinderConfig extends ConfigObject
{
    /**
     * Constructor.
     */
    public function __construct(User $user)
    {
        $params = ComponentHelper::getParams('com_media');

        // allow all allowable file extensions and MIME types in input field
        $accept = [];

        $parseValues = fn($param) => array_filter(
            array_map('trim', explode(',', $params->get($param, ''))),
            fn($value) => $value !== '',
        );

        if ($params->get('restrict_uploads', true)) {
            $restricted = $parseValues('restrict_uploads_extensions');
            array_push($accept, ...array_map(fn($extension) => ".{$extension}", $restricted));

            if ($params->get('check_mime', true)) {
                array_push($accept, ...$parseValues('upload_mime'));
            }
        }

        parent::__construct([
            'accept' => implode(',', $accept),
            'roots' => Media::getRootPaths(),
            'canCreate' =>
                $user->authorise('core.manage', 'com_media') ||
                $user->authorise('core.create', 'com_media'),
            'canDelete' =>
                $user->authorise('core.manage', 'com_media') ||
                $user->authorise('core.delete', 'com_media'),
        ]);
    }
}
