<?php

namespace FSPoster\App\Watermark\App;

use Exception;
use FSPoster\App\Providers\Core\RestRequest;
use FSPoster\App\Providers\Core\Settings;
use FSPoster\App\Providers\Helpers\PluginHelper;
use FSPoster\App\Watermark\Api\Api;
use FSPoster\App\Watermark\App\Mappers\SaveWatermarkRequestMapper;
use FSPoster\App\Watermark\App\Mappers\WatermarkRulesArrayMapper;

class Controller
{
    public static function saveWatermarkSettings(RestRequest $request): array
    {
        if (! PluginHelper::canAccessToSettings()) {
            return [];
        }

        try {
            $dto = (new SaveWatermarkRequestMapper())->fromRequest($request);
        } catch (Exception $e) {
            return ['error_msg' => $e->getMessage()];
        }

        Settings::set('watermark_enabled', (int) $dto->watermarkEnabled);
        Settings::set('watermark_rendering_fails', $dto->watermarkRenderingFails);
        Settings::set('watermark_rules', (new WatermarkRulesArrayMapper())->toArray($dto->rules));

        return [];
    }

    /**
     * @throws Exception
     */
    public static function deleteWatermarkRule(RestRequest $request): array
    {
        if (! PluginHelper::canAccessToSettings()) {
            return [];
        }

        $ruleId = $request->require('rule_id', RestRequest::TYPE_STRING, fsp__('Rule ID is required'));

        $rules = Settings::get('watermark_rules', []);

        if (!is_array($rules)) {
            $rules = [];
        }

        $rules = array_values(array_filter($rules, function ($rule) use ($ruleId) {
            return isset($rule['id']) && $rule['id'] !== $ruleId;
        }));

        Settings::set('watermark_rules', $rules);

        return [];
    }

    public static function getWatermarkSettings(RestRequest $request): array
    {
        if (! PluginHelper::canAccessToSettings()) {
            return [];
        }

        $watermarkEnabled = (bool) Settings::get('watermark_enabled', 0);
        $watermarkRenderingFails = Settings::get('watermark_rendering_fails', 'original');
        $rules = Settings::get('watermark_rules', []);

        if (!is_array($rules)) {
            $rules = [];
        }

        return [
            'watermark_enabled' => $watermarkEnabled,
            'watermark_rendering_fails' => $watermarkRenderingFails,
            'rules' => $rules,
        ];
    }

    public static function getWatermarkUsage(RestRequest $request): array
    {
        if (! PluginHelper::canUserAccessToPlugin()) {
            return [];
        }

        $result = (new Api())->getWatermarkUsage();

        if (! $result->success) {
            return ['error_msg' => $result->errorMessage];
        }

        return [
            'usage' => [
                'image' => $result->image,
                'video' => $result->video,
            ],
        ];
    }
}
