<?php

namespace KupShop\I18nBundle\Admin\lists;

use Doctrine\DBAL\Query\QueryBuilder;
use KupShop\I18nBundle\Translations\BlocksTranslation;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class TranslateBlocksList extends TranslateList
{
    protected $template = 'list/translateBlocks.tpl';

    protected $listType = 'translateBlocks';

    public function __construct()
    {
        parent::__construct();
        $this->translation = ServiceContainer::getService(BlocksTranslation::class);
    }

    public function applyFilters(QueryBuilder $qb)
    {
        $qb = parent::applyFilters($qb);
        if ($templateBlockIDs = getVal('blocks', null, [])) {
            $qb->andWhere(
                Operator::inIntArray($templateBlockIDs, $this->translation->getTableAlias().'.id_root')
            );
            $qb->addOrderBy($this->translation->getTableAlias().'.position');
        }

        return $qb;
    }

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

        // prepare texts
        $newSQL = [];
        foreach ($data['SQL'] as $object) {
            $newSQL[] = $this->prepareTextBlocks($object);
        }

        $data['SQL'] = $newSQL;

        return $data;
    }

    protected function prepareTextBlocks($object)
    {
        foreach ($this->sourceLanguages as $language => $_) {
            $prefix = $language.'_';
            if ($this->languageContext->getDefaultId() == $language) {
                $prefix = '';
            }
            $json_content = isset($object[$prefix.'json_content']) ? json_decode($object[$prefix.'json_content'], true) : null;
            if ($json_content) {
                $text_blocks = [];
                BlocksTranslation::getTextBlocks($json_content, $text_blocks);
                $object[$prefix.'json_content'] = $text_blocks;
            } else {
                $object[$prefix.'json_content'] = $json_content;
            }
        }

        // translateLanguages - array contains ids of selected language and selected source language (if it is not the default one)
        $prefix_source = (count($this->translateLanguages) == 1) ? '' : $this->translateLanguages[0].'_';
        $prefix_target = $this->translateLanguages[count($this->translateLanguages) - 1].'_';
        if (!empty($object[$prefix_source.'json_content'])) {
            // If target not translated yet, all source blocks are translatable
            if (is_null($object[$prefix_target.'json_content']) || (is_array($object[$prefix_target.'json_content']) && empty($object[$prefix_target.'json_content']))) {
                // pokud tam kopiruju stejnej content jako ve zdroji, tak aspon resetuju settingy, abych videl, ze to neni prelozeny
                $object[$prefix_target.'json_content'] = $this->resetBlockSettings($object[$prefix_source.'json_content'] ?? []);
            }
        }

        // pokud neco chybelo ve vychozim jazyce, tak se to potom nezobrazilo v prekladech
        // touhle upravou ty prelozene bloky prenesu do defaultu s prazdnym obsahem, abych to aspon zobrazil
        $translatedContent = $this->resetBlockSettings($object[$this->language.'_json_content'] ?? []);
        $object['json_content'] = array_replace($translatedContent, $object['json_content'] ?: []);

        return $object;
    }

    private function resetBlockSettings(array $blocks): array
    {
        foreach ($blocks as &$item) {
            $item['settings'] = [];
        }

        return $blocks;
    }
}

$main_class = TranslateBlocksList::class;
