<?php

namespace FiloBlu\Refilo\Model\Exporter;

use Blackbird\ContentManager\Model\ResourceModel\Content\CollectionFactory;
use FiloBlu\Core\Model\Configuration;
use FiloBlu\Refilo\Helper\ContentManager\Data as ContentManagerHelper;
use FiloBlu\Refilo\Model\Adapter\Mongo;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;

/**
 * Class ContentManager
 * @package FiloBlu\Refilo\Model\Exporter
 */
class ContentManager extends AbstractCmsExporter
{
    /**
     * @var CollectionFactory
     */
    protected $contentCollectionFactory;
    /**
     * @var
     */
    protected $contentTypes;

    /**
     * @var ContentManagerHelper
     */
    private $contentManagerHelper;
    /**
     * @var \Blackbird\ContentManager\Model\ResourceModel\ContentType\CustomField\CollectionFactory
     */
    private $collectionFactory;

    /**
     * @var array | null
     */
    private $fieldTypeLookup;

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \FiloBlu\Refilo\Model\Adapter\Mongo $mongo
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Blackbird\ContentManager\Model\ResourceModel\Content\CollectionFactory $contentCollectionFactory
     * @param \FiloBlu\Refilo\Helper\ContentManager\Data $contentManagerHelper
     * @param \FiloBlu\Core\Model\Configuration $coreConfiguration
     * @param \Blackbird\ContentManager\Model\ResourceModel\ContentType\CustomField\CollectionFactory $collectionFactory
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        Mongo $mongo,
        StoreManagerInterface $storeManager,
        CollectionFactory $contentCollectionFactory,
        ContentManagerHelper $contentManagerHelper,
        Configuration $coreConfiguration,
        \Blackbird\ContentManager\Model\ResourceModel\ContentType\CustomField\CollectionFactory $collectionFactory
    ) {
        parent::__construct($mongo, $coreConfiguration, $scopeConfig, $storeManager);
        $this->contentCollectionFactory = $contentCollectionFactory;
        $this->contentManagerHelper = $contentManagerHelper;
        $this->collectionFactory = $collectionFactory;
    }

    public function getMetaCode(): string
    {
        return 'master_data';
    }

    public function getCollectionPrefix(): string
    {
        return 'master_data_';
    }

    /**
     * @throws LocalizedException
     */
    public function execute(OutputInterface $output = null)
    {
        $this->fieldTypeLookup = [];

        foreach ($this->collectionFactory->create() as $customField) {
            $this->fieldTypeLookup[$customField->getType()][] = $customField->getIdentifier();
        }

        foreach ($this->getStoreManager()->getStores() as $store) {
            $projectId = $this->getDatabaseByWebsiteCode($store->getWebsite()->getCode());

            if (!$projectId) {
                continue;
            }

            $bulkData = [];
            $result = $this->contentCollectionFactory->create()->addStoreFilter($store)->addAttributeToSelect('*');
            foreach ($result as $item) {
                $itemIdentifier = $this->contentManagerHelper->getIdentifierFromId($item->getData('ct_id'));

                $bulkData[] = [
                    '_id'             => $itemIdentifier . '_' . $item->getId() . '_' . $store->getData('code'),
                    'metacode'        => 'master_data',
                    'contentmetacode' => $itemIdentifier,
                    'idx'             => $item->getId(),
                    'metadata'        => $this->getContentMetadata($item->getData('ct_id'), $item)
                ];
            }

            try {
                $this->getConnection()->update(
                    '_id',
                    $bulkData,
                    'master_data_' . $store->getCode(),
                    true,
                    $projectId
                );
            } catch (Throwable $throwable) {
                echo $throwable->getMessage();
            }
        }
    }

    /**
     * @param $ctId
     * @param $item
     * @return array
     */
    public function getContentMetadata($ctId, $item)
    {
        $data = array_merge($this->contentManagerHelper->getDataFromId($ctId), $item->getData());

        if (empty($data['meta_description'])) {
            $data['meta_description'] = $data['description'];
        }

        // Ensure types

        if (isset($this->fieldTypeLookup['integer'])) {
            foreach ($this->fieldTypeLookup['integer'] as $field) {
                if (!isset($data[$field])) {
                    continue;
                }

                $data[$field] = (int)$data[$field];
            }
        }

        return $data;
    }
}
