<?php

namespace FiloBlu\Refilo\Model\Exporter;

use FiloBlu\Core\Model\Configuration;
use FiloBlu\Refilo\Helper\Data;
use FiloBlu\Refilo\Model\Adapter\Mongo;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\State;
use Magento\Framework\Translate;
use Magento\Framework\Translate\ResourceInterface;
use Magento\Store\Api\StoreConfigManagerInterface;
use MongoDB\Driver\Exception\Exception;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class Translations
 * @package FiloBlu\Refilo\Model\Exporter
 */
class Translations extends AbstractExporter
{
    /**
     * @var Translate
     */
    private $translate;
    /**
     * @var Data
     */
    private $helperData;


    /**
     * Translations constructor.
     * @param ScopeConfigInterface $scopeConfig
     * @param ResourceInterface $translate
     * @param Mongo $mongo
     * @param Configuration $coreConfiguration
     * @param Data $helperData
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        ResourceInterface $translate,
        Mongo $mongo,
        Configuration $coreConfiguration,
        Data $helperData
    ) {
        parent::__construct($mongo, $coreConfiguration, $scopeConfig);
        $this->translate = $translate;
        $this->helperData = $helperData;
    }

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

    /**
     * @throws Exception|\Magento\Framework\Exception\LocalizedException
     */
    public function execute(OutputInterface $output = null)
    {
        $id = 1;

        foreach ($this->helperData->getLocales() as $locale) {
            $bulkData = [];
            $data = $this->translate->getTranslationArray(null, $locale);

            foreach ($data as $string => $translation) {
                $bulkData[] = [
                    '_id'         => $id++,
                    'string'      => $string,
                    'translation' => strtr($translation, ['&#039;' => '\'']),
                    'locale_code' => $locale
                ];
            }

            $this->write($bulkData);
        }
    }

    /**
     * @param array $bulkData
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function write(array $bulkData)
    {
        if (empty($bulkData)) {
            return;
        }

        $projectIds = [$this->getDatabase()];

        if ($this->getCoreConfiguration()->isMultiDomain()) {
            $projectIds = $this->getCoreConfiguration()->getProjectIds();
        }

        try {
            foreach ($projectIds as $projectId) {
                $this->getConnection()->update('_id', $bulkData, 'translations', true, $projectId);
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}
