<?php

namespace FSPoster\App\Watermark\App\Mappers;

use FSPoster\App\Watermark\App\DTOs\Request\ImageWatermarkOptions;
use FSPoster\App\Watermark\App\DTOs\Request\TextWatermarkOptions;
use FSPoster\App\Watermark\App\DTOs\Request\WatermarkOptions;
use FSPoster\App\Watermark\App\DTOs\Request\WatermarkRule;

class WatermarkRulesArrayMapper
{
    /**
     * @param WatermarkRule[] $rules
     */
    public function toArray(array $rules): array
    {
        return array_map([$this, 'ruleToArray'], $rules);
    }

    public function ruleToArray(WatermarkRule $rule): array
    {
        return [
            'id'        => $rule->id,
            'name'      => $rule->name,
            'enabled'   => $rule->enabled,
            'applyType' => $rule->applyType,
            'filters'   => [
                'mediaTypes'     => $rule->filters->mediaTypes,
                'socialNetworks' => $rule->filters->socialNetworks,
            ],
            'options'   => $this->optionsToArray($rule->options),
        ];
    }

    private function optionsToArray(WatermarkOptions $options): array
    {
        if ($options instanceof ImageWatermarkOptions) {
            return $this->imageOptionsToArray($options);
        }

        if ($options instanceof TextWatermarkOptions) {
            return $this->textOptionsToArray($options);
        }

        return [];
    }

    private function imageOptionsToArray(ImageWatermarkOptions $options): array
    {
        return [
            'position'     => $options->position,
            'vertical'     => $options->vertical,
            'horizontal'   => $options->horizontal,
            'imageId'      => $options->imageId,
            'imageUrl'     => $options->imageUrl,
            'imageSize'    => $options->imageSize,
            'imageOpacity' => $options->imageOpacity,
        ];
    }

    private function textOptionsToArray(TextWatermarkOptions $options): array
    {
        return [
            'position'      => $options->position,
            'vertical'      => $options->vertical,
            'horizontal'    => $options->horizontal,
            'textValue'     => $options->textValue,
            'textAlignment' => $options->textAlignment,
            'textOpacity'   => $options->textOpacity,
            'bgOpacity'     => $options->bgOpacity,
            'fontSize'      => $options->fontSize,
            'fontFamily'    => $options->fontFamily,
            'textColor'     => $options->textColor,
            'bgColor'       => $options->bgColor,
            'textWidth'     => $options->textWidth,
        ];
    }
}
