<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Jet Theme Backend for Magento 2 (System)
 */

namespace Amasty\JetTheme\Model\Config\Backend;

use Magento\Framework\App\Config\Data\ProcessorInterface;
use Magento\Framework\App\Config\Value;
use Magento\Framework\Exception\LocalizedException;

class Width extends Value implements ProcessorInterface
{
    private const WIDTH_FIELD_DEFAULT_MAP = [
        'layout_width' => '1440px',
        'indent_width' => '30px',
    ];

    /**
     * @return void
     * @throws LocalizedException
     */
    public function beforeSave(): void
    {
        if (empty((string)$this->getValue())) {
            $field = $this->getData('field_config')['id'];
            $defaultValue = self::WIDTH_FIELD_DEFAULT_MAP[$field];
            $this->setValue($defaultValue);
        }

        $value = (string)$this->getValue();

        if (!$this->validateValue($value)) {
            $fieldLabel = $this->getData('field_config')['label'] ?? '';
            throw new LocalizedException(__('%1 value must be in format (100% or 1024px for example)', $fieldLabel));
        }
    }

    /**
     * @param string $value
     * @return string
     */
    public function processValue($value): string
    {
        return $value;
    }

    private function validateValue(string $value): bool
    {
        return preg_match('/^([\d]{1,3}\%)|([\d]{1,4}px)$/i', $value) === 1;
    }
}
