<?php

namespace KupShop\RecommendersBundle\Admin;

use KupShop\AdminBundle\Admin\ProductsFilter;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\System\BundleFinder;
use KupShop\RecommendersBundle\Recommenders\RecommendersLocator;

class Recommenders extends \Window
{
    protected $tableName = 'recommenders';
    protected $nameField = 'title';
    protected $uniques = ['label' => 'label'];

    protected RecommendersLocator $recommendersLocator;

    public function __construct()
    {
        $this->recommendersLocator = ServiceContainer::getService(RecommendersLocator::class);
    }

    public function get_vars()
    {
        $vars = parent::get_vars();

        $recommenders = $this->recommendersLocator->getRecommenders();
        $vars['recommenders'] = array_map(fn ($r) => $r->getName(), $recommenders);
        $this->unserializeCustomData($vars['body']['data']);
        $this->getRecommendersData($vars['body']['data']);

        return $vars;
    }

    public function getData()
    {
        $data = parent::getData();

        $this->cleanData($data);
        if (!empty($data['data']['fallback'])) {
            $this->cleanData($data['data']['fallback']);
        }

        if (getVal('Submit')) {
            $this->serializeCustomData($data);
        }

        return $data;
    }

    public function serializeCustomData(&$data)
    {
        if (empty($data['data']['cache']) && $data['data']['cache'] === '') {
            unset($data['data']['cache']);
        }

        parent::serializeCustomData($data);
    }

    protected function cleanData(&$data): void
    {
        $type = $data['type'] ?? null;
        if (($type == 'products_filter') && ($filter = $data['data']['filter'] ?? null)) {
            $data['data']['filter'] = ProductsFilter::cleanFilter($filter);
        }
    }

    public function getRecommendersData(array &$data)
    {
        if ($type = $data['type'] ?? null) {
            $data['recommender'] = $recommender = $this->recommendersLocator->getRecommender($type);
            $data['configurationTemplate'] = $this->getConfigurationTemplate($recommender->getTemplate());
        }

        return $data;
    }

    protected function getConfigurationTemplate(?string $template): ?string
    {
        $bundleFinder = ServiceContainer::getService(BundleFinder::class);

        if ($existing = $bundleFinder->getExistingBundlesPath('Admin/templates/window/'.$template)) {
            $bundles = array_keys($existing);

            return '['.reset($bundles).']/window/'.$template;
        }

        return null;
    }

    public function hasRights($name = null)
    {
        return match ($name) {
            \Window::RIGHT_DELETE, \Window::RIGHT_DUPLICATE => isSuperuser(),
            default => parent::hasRights($name),
        };
    }
}

return Recommenders::class;
