<?php

declare(strict_types=1);

namespace PHPNative\Tailwind\Parser;

class Gap implements Parser
{
    public static function parse(string $style): ?\PHPNative\Tailwind\Style\Gap
    {
        $x = null;
        $y = null;

        // gap-{n} - both x and y
        preg_match_all('/\bgap-(\d+)\b/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            $value = (int)$output_array[1][0] * 4; // Tailwind uses a 4px scale
            $x = $value;
            $y = $value;
        }

        // gap-x-{n}
        preg_match_all('/\bgap-x-(\d+)\b/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            $x = (int)$output_array[1][0] * 4;
        }

        // gap-y-{n}
        preg_match_all('/\bgap-y-(\d+)\b/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            $y = (int)$output_array[1][0] * 4;
        }

        if ($x !== null || $y !== null) {
            return new \PHPNative\Tailwind\Style\Gap($x ?? 0, $y ?? 0);
        }

        return null;
    }

    public static function merge(\PHPNative\Tailwind\Style\Gap $class, \PHPNative\Tailwind\Style\Gap $style)
    {
        if ($style->x !== 0) {
            $class->x = $style->x;
        }
        if ($style->y !== 0) {
            $class->y = $style->y;
        }
    }
}
