<?php

namespace PHPNative\Tailwind;

use PHPNative\Renderer\Cache\Styles;
use PHPNative\Renderer\Viewport;
use PHPNative\Tailwind\Style\DirectionEnum;
use PHPNative\Tailwind\Style\Flex;
use PHPNative\Tailwind\Style\FlexTypeEnum;
use PHPNative\UI\View;

class LayoutParser
{

    public static function sortByStyles(Styles $stylesCache, View $container, Viewport $viewport): View
    {
        $i = 0;
        $flexOne = 0;
        $container->getViews()->map(function (View $a) use (&$flexOne, &$i, &$stylesCache, $viewport) {
            $aStyles = $stylesCache->getStyle($a->getId(), $viewport->windowMediaQuery, $a->getState(), $a->getStyle());
            if(isset($aStyles[Flex::class]) && $aStyles[Flex::class]->type == FlexTypeEnum::one) {
                $flexOne++;
            }
            $a->setRenderSort($i);
            $i++;
        });

        $container->getViews()->sort(function (View $a, View $b) use (&$stylesCache, $viewport) {
            $aStyles = $stylesCache->getStyle($a->getId(), $viewport->windowMediaQuery, $a->getState(), $a->getStyle());
            $bStyles = $stylesCache->getStyle($b->getId(), $viewport->windowMediaQuery, $b->getState(), $b->getStyle());
            if(isset($aStyles[Flex::class]) && $aStyles[Flex::class]->type == FlexTypeEnum::none &&
                isset($bStyles[Flex::class]) && $bStyles[Flex::class]->type == FlexTypeEnum::one) {
                return -1;
            }

            return 1;
        });

        $container->getViews()->countOne = $flexOne;

        return $container;

    }

    public static function sortByRenderSort(View $container)
    {
        $container->getViews()->sort(function (View $a, View $b)  {
            if($a->getRenderSort() == $b->getRenderSort()) {
                return 0;
            }

            return $a->getRenderSort() <=> $b->getRenderSort();
        });
    }
}