<?php

namespace FiloBlu\Refilo\Model\Exporter;

use FiloBlu\Core\Model\Configuration;
use FiloBlu\Refilo\Model\Adapter\Mongo;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Store\Model\StoreManagerInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class Menu
 * @package FiloBlu\Refilo\Model\Exporter
 */
class Menu extends AbstractExporter
{
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var Configuration
     */
    private $coreConfiguration;

    /**
     * Menu constructor.
     * @param ResourceConnection $resourceConnection
     * @param ScopeConfigInterface $scopeConfig
     * @param Mongo $mongo
     * @param Configuration $coreConfiguration
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        ResourceConnection $resourceConnection,
        ScopeConfigInterface $scopeConfig,
        Mongo $mongo,
        Configuration $coreConfiguration,
        StoreManagerInterface $storeManager
    ) {
        parent::__construct($mongo, $coreConfiguration, $scopeConfig);
        $this->resourceConnection = $resourceConnection;
        $this->storeManager = $storeManager;
        $this->coreConfiguration = $coreConfiguration;
    }

    /**
     * @return iterable
     */
    public function getCollections(): iterable
    {
        yield 'menus';
    }

    /**
     * @param \Symfony\Component\Console\Output\OutputInterface|null $output
     * @return void
     * @throws \Magento\Framework\Exception\LocalizedException
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function execute(OutputInterface $output = null)
    {
        $isMultiDomain = $this->coreConfiguration->isMultiDomain();

        $databaseMap = [];

        if ($isMultiDomain) {
            foreach ($this->coreConfiguration->getWebsiteMapping() as $map) {
                foreach ($map->getWebsiteCodes() as $websiteCode) {
                    $databaseMap[$websiteCode] = $map->getProjectId();
                }
            }
        } else {
            foreach ($this->storeManager->getStores() as $value) {
                $databaseMap[$value->getWebsite()->getCode()] = $this->getDatabase();
            }
        }

        $_id = 1;
        foreach ($this->storeManager->getStores() as $store) {
            // If this store is not configured to be handled then skip it
            if (!isset($databaseMap[$store->getWebsite()->getCode()])) {
                continue;
            }

            $bulkData = [];
            $storeId = $store->getData('store_id');
            $query = "SELECT bmn.*,bmm.title AS menu_title, bmm.identifier AS code FROM blackbird_menumanager_node AS bmn
                                INNER JOIN blackbird_menumanager_menu AS bmm ON bmm.menu_id=bmn.menu_id
                                INNER JOIN blackbird_menumanager_store AS bms ON bms.menu_id=bmm.menu_id AND store_id IN ($storeId,0)
                                WHERE bmn.is_active = 1";

            $result = $this->resourceConnection->getConnection()->fetchAll($query);
            foreach ($result as $item) {
                $menu = new \stdClass();

                $menu->_id = $_id;
                $menu->node_id = (int)$item['node_id'];
                $menu->code = $item['code'];
                $menu->type = $item['type'];
                $menu->object_id = $item['entity_id'];
                $menu->parent_id = (int)$item['parent_id'];
                $menu->position = (int)$item['position'];
                $menu->level = (int)$item['level'];
                $menu->title = html_entity_decode($item['title']);
                $menu->menu_title = $item['menu_title'];
                $menu->target = $item['target'];
                $menu->url = $item['url_path'];
                $menu->css_classes = $item['classes'];
                $menu->customer_group = $item['customer_group'] != null ? explode(',', $item['customer_group']) : null;
                $menu->max_items_for_column =  $item['max_item_column'];
                $menu->enabled =  (bool)$item['is_active'];
                $menu->store = $store->getData('code');
                $menu->identifier = $item['identifier'] ?? null;

                $bulkData[] = $menu;
                $_id++;
            }


            try {
                $this->getConnection()->update(
                    '_id',
                    $bulkData,
                    'menus',
                    true,
                    $databaseMap[$store->getWebsite()->getCode()]
                );
            } catch (\MongoDB\Driver\Exception\Exception $e) {
                echo $e->getMessage();
            }
        }
    }
}
