<?php

declare(strict_types=1);

namespace PHPNative\Tailwind\Parser;

use PHPNative\Tailwind\Style\AlignEnum;

class Text implements Parser
{
    public static function parse(string $style): ?\PHPNative\Tailwind\Style\Text
    {
        $color = new \PHPNative\Tailwind\Style\Color();

        preg_match_all('/text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            $size = match ((string)$output_array[1][0]) {
                'xs' => 12,
                'sm' => 14,
                'base' => 16,
                'lg' => 18,
                'xl' => 20,
                '2xl' => 24,
                '3xl' => 30,
                '4xl' => 36,
                '5xl' => 48,
                '6xl' => 60,
                '7xl' => 72,
                '8xl' => 96,
                '9xl' => 128,
            };
            return new \PHPNative\Tailwind\Style\Text(size: $size);
        }

        preg_match_all('/text-(center|right|left)/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            return match ((string)$output_array[1][0]) {
                'left' => new \PHPNative\Tailwind\Style\Text(align: AlignEnum::left),
                'right' => new \PHPNative\Tailwind\Style\Text(align: AlignEnum::right),
                'center' => new \PHPNative\Tailwind\Style\Text(align: AlignEnum::center),
            };
        }

        preg_match_all('/text-(.*)/', $style, $output_array);
        if (count($output_array[0]) > 0) {
            $colorStyle = $output_array[1][0];
            $color = Color::parse($colorStyle);
            return new \PHPNative\Tailwind\Style\Text($color);
        }

        return null;
    }

    public static function merge(\PHPNative\Tailwind\Style\Text $style1, \PHPNative\Tailwind\Style\Text $style2): void
    {
        if($style2->color->red != -1) {
            $style1->color->red = $style2->color->red;
        }
        if($style2->color->green != -1) {
            $style1->color->green = $style2->color->green;
        }
        if($style2->color->blue != -1) {
            $style1->color->blue = $style2->color->blue;
        }
        if($style2->color->alpha != -1) {
            $style1->color->alpha = $style2->color->alpha;
        }
        if($style2->size != 16) {
            $style1->size = $style2->size;
        }
        if($style2->align != AlignEnum::left) {
            $style1->align = $style2->align;
        }
    }
}
