<?php
/**
 * Abstract Variable Processor
 *
 * @package Brandy\DynamicCss\Processors
 */

namespace Brandy\DynamicCss\Processors;

use Brandy\DynamicCss\ResponsiveHelper;
use Brandy\DynamicCss\VariableProcessorInterface;
use Brandy\Utils\Helpers;
use Brandy\Utils\StylesDataHelpers;

/**
 * Base class for CSS variable processors
 */
abstract class AbstractVariableProcessor implements VariableProcessorInterface {

	/**
	 * Responsive helper instance
	 *
	 * @var ResponsiveHelper
	 */
	protected ResponsiveHelper $responsive_helper;

	/**
	 * Constructor
	 *
	 * @param ResponsiveHelper $responsive_helper Responsive helper instance.
	 */
	public function __construct( ResponsiveHelper $responsive_helper ) {
		$this->responsive_helper = $responsive_helper;
	}

	/**
	 * Process responsive or non-responsive variable data
	 *
	 * @param array    $variable_data Variable configuration.
	 * @param callable $get_css_var   Callback to generate CSS variable from value.
	 * @return array Device-keyed CSS variables
	 */
	protected function process_responsive( array $variable_data, callable $get_css_var ): array {
		$result   = $this->responsive_helper->get_empty_device_result();
		$selector = $variable_data['selector'] ?? '';
		$value    = $variable_data['value'];

		if ( StylesDataHelpers::is_responsive_data( $value ) ) {
			foreach ( $value as $device => $variable_value ) {
				if ( ! in_array( $device, brandy_get_devices(), true ) ) {
					continue;
				}
				$variable_value = Helpers::get_device_value( $value, $device );
				$css_var        = $get_css_var( $variable_data, $variable_value );
				$this->responsive_helper->add_to_result( $result, $device, $selector, $css_var );
			}
		} else {
			$css_var = $get_css_var( $variable_data, $value );
			$this->responsive_helper->add_to_result( $result, 'desktop', $selector, $css_var );
		}

		return $result;
	}
}
