<?php
/**
 * @package DJ-Catalog2-Yootheme
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

namespace DJExtensions\DJCatalog2\YOOtheme\Layouts;
defined('_JEXEC') or die;
use function YOOtheme\app;
use YOOtheme\Config;

class LayoutTransform
{
    /**
     * Transform callback.
     *
     * @param object $node
     * @param array  $params
     */
    public function __invoke($node, array $params)
    {
        /**
         * @var Layouts $layouts
         * @var Config $config
         */
        list($layouts, $config) = app(Layouts::class, Config::class);

        // expected layouts are layout as a list set on node
        $list = $node->djcatalog2Layouts ?? false;

        // fallback to retrieve on render
        if ($config('app.isCustomizer') || !$list) {

            // a fallback for pre v1.1.0, when the list was not being layout
            foreach ($layouts->retrieveLayouts($node, $params['type']) as $layout) {
                $layouts->load($layout, $params);
            }

            if ($config('app.isCustomizer')) {
                foreach ($layouts->retrieveLayoutsHtml($node, $params['type']) as $layout) {
                    $layouts->load($layout, $params);
                }
            }
            return;
        }

        if ($list = $node->djcatalog2Layouts ?? false) {
            foreach ($list as $layout) {
                $layouts->load($layout, $params);
            }
        }
    }
}
