<?php

declare(strict_types=1);

namespace PHPNative\Tailwind\Parser;

class Padding implements Parser
{
    public static function parse(string $style): ?\PHPNative\Tailwind\Style\Padding
    {
        $l = null;
        $r = null;
        $t = null;
        $b = null;

        preg_match_all('/\bp-(\d*)\b/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            // Tailwind uses a 4px scale
            $l = (int)$output_array[1][0] * 4;
            $r = (int)$output_array[1][0] * 4;
            $t = (int)$output_array[1][0] * 4;
            $b = (int)$output_array[1][0] * 4;
        }

        preg_match_all('/\bpx-(\d*)\b/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            $l = (int)$output_array[1][0] * 4;
            $r = (int)$output_array[1][0] * 4;
        }

        preg_match_all('/\bpy-(\d*)\b/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            $t = (int)$output_array[1][0] * 4;
            $b = (int)$output_array[1][0] * 4;
        }

        preg_match_all('/\bpt-(\d*)\b/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            $t = (int)$output_array[1][0] * 4;
        }

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

        preg_match_all('/\bpl-(\d*)\b/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            $l = (int)$output_array[1][0] * 4;
        }

        preg_match_all('/\bpr-(\d*)\b/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            $r = (int)$output_array[1][0] * 4;
        }

        if($l != null || $r != null || $t != null || $b != null) {
            return new \PHPNative\Tailwind\Style\Padding($l, $r, $t, $b);
        }

        return null;
    }

    public static function merge(\PHPNative\Tailwind\Style\Padding $class, \PHPNative\Tailwind\Style\Padding $style)
    {
        if($style->left != null) {
            $class->left = $style->left;
        }
        if($style->right != null) {
            $class->right = $style->right;
        }
        if($style->top != null) {
            $class->top = $style->top;
        }
        if($style->bottom != null) {
            $class->bottom = $style->bottom;
        }
    }
}
