<?php

namespace KupShop\ContentBundle\Util;

use Doctrine\ORM\EntityManagerInterface;
use KupShop\ContentBundle\Entity\Wrapper\BlockWrapper;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class InlineEdit
{
    private $block;
    private $entityManager;

    public function __construct(Block $block, EntityManagerInterface $entityManager)
    {
        $this->block = $block;
        $this->entityManager = $entityManager;
    }

    /**
     * @param $block BlockWrapper|array
     *
     * @return BlockWrapper|array
     */
    public function wrapBlock($block)
    {
        static $counter = 0;

        if (!getAdminUser()) {
            return $block;
        }

        if (($block instanceof BlockWrapper && $block['isWrapped']) || ($block['isWrapped'] ?? false)) {
            return $block;
        }

        if (isset($block['id_object']) && isset($block['type'])) {
            $block = $this->createBlock($block['id_object'], $block['type']);
        }

        $jsonContent = $block['json_content'];
        if (empty($jsonContent)) {
            $jsonContent = json_encode([]);
        }

        $id_language = '';
        $languageContext = ServiceContainer::getService(LanguageContext::class);
        if ($languageContext->translationActive()) {
            $id_language = ' data-kupshop-language-id=\''.$languageContext->getActiveId().'\'';
        }

        $block['isWrapped'] = true;
        $block['unwrapped_content'] = $block['content'];
        $object_info = $block['object_info'] ?? '';
        $block['content'] = '<div data-kupshop-block-id=\''.$block['id'].'\''.$id_language.' data-blocek-editable data-block-title=\''.htmlspecialchars($block['name']).'\' data-blocek-id=\''.$counter++.'\' data-blocek-object-info="'.htmlspecialchars($object_info).'" data-blocek-source="'.htmlspecialchars($jsonContent).'">'.$block['content'].'</div>';

        if (!empty($block['children'])) {
            foreach ($block['children'] as &$child) {
                $child['object_info'] = $object_info;
                $child = $this->wrapBlock($child);
            }
        }

        return $block;
    }

    public function createBlock($objectID, $type)
    {
        $blocks = sqlGetConnection()->transactional(function () use ($objectID, $type) {
            $rootId = $this->block->insertFirstBlock($type, $objectID, '', true);

            return $this->block->getBlocks($rootId);
        });

        return reset($blocks);
    }

    public function createBlockForEntity($objectID, $type)
    {
        $block = $this->createBlock($objectID, $type);
        if (!$block) {
            return null;
        }

        $entity = $this->entityManager->getRepository(\KupShop\ContentBundle\Entity\Block::class);

        return $entity->find($block['id_root']);
    }

    public function insertBlockForEntity($rootID)
    {
        sqlQueryBuilder()
            ->insert('blocks')
            ->directValues(['id_parent' => $rootID, 'id_root' => $rootID, 'content' => ''])
            ->execute();

        $entity = $this->entityManager->getRepository(\KupShop\ContentBundle\Entity\Block::class);

        $block = $entity->find($rootID);
        // ten root block je cached, takze to ho potrebuju refreshnout, aby se mi vratil v aktualizovane podobe
        $this->entityManager->refresh($block);

        return $entity->find($rootID);
    }
}
