<?php

namespace PHPNative\Tailwind\Model;

use PHPNative\Core\TypedCollection;
use PHPNative\Tailwind\Style\Border;
use PHPNative\Tailwind\Style\Flex;
use PHPNative\Tailwind\Style\Margin;
use PHPNative\Tailwind\Style\MediaQueryEnum;
use PHPNative\Tailwind\Style\Padding;
use PHPNative\Tailwind\Style\StateEnum;
use PHPNative\Tailwind\Style\Text;

class StyleCollection extends TypedCollection
{
    protected function type(): string
    {
        return Style::class;
    }

    public function getValidStyles(MediaQueryEnum $mediaQueryEnum, StateEnum $state): array
    {
        $items = [];

        foreach($this->items() as $style) {
            if(($style->state == StateEnum::normal || $style->state === $state) && ($style->mediaQuery->value === 0 || $style->mediaQuery->value <= $mediaQueryEnum->value)) {
                $items[] = $style;
            }
        }

        return $this->merge($items);
    }

    private function merge(array $styles): array
    {
        $tmp = [];

        foreach($styles as $style) {
            if(isset($tmp[$style->style::class]) && $style->style::class === Padding::class) {
                \PHPNative\Tailwind\Parser\Padding::merge($tmp[$style->style::class], $style->style);
            }elseif(isset($tmp[$style->style::class]) && $style->style::class === Margin::class) {
                \PHPNative\Tailwind\Parser\Margin::merge($tmp[$style->style::class], $style->style);
            }elseif(isset($tmp[$style->style::class]) && $style->style::class === Border::class) {
                \PHPNative\Tailwind\Parser\Border::merge($tmp[$style->style::class], $style->style);
            }elseif(isset($tmp[$style->style::class]) && $style->style::class === Text::class) {
                \PHPNative\Tailwind\Parser\Text::merge($tmp[$style->style::class], $style->style);
            }elseif(isset($tmp[$style->style::class]) && $style->style::class === Flex::class) {
                \PHPNative\Tailwind\Parser\Flex::merge($tmp[$style->style::class], $style->style);
            }elseif(isset($tmp[$style->style::class]) && $style->style::class === \PHPNative\Tailwind\Style\Shadow::class) {
                \PHPNative\Tailwind\Parser\Shadow::merge($tmp[$style->style::class], $style->style);
            }else{
                $tmp[$style->style::class] = $style->style;
            }
        }

        return $tmp;
    }

    public function __clone()
    {
        $cloned = [];
        foreach ($this->items() as $style) {
            $cloned[] = clone $style;
        }

        $this->setElements($cloned);
    }
}
