<?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 MongoDB\Driver\Exception\Exception;
use stdClass;
use Symfony\Component\Console\Output\OutputInterface;

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

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

    public function preExecute(OutputInterface $output = null)
    {
        // TODO: drop only metacode = country
        // foreach ($this->getCollections() as $collection) {
        //     $this->getConnection()->deleteDocumentsByProperties(
        //         $this->getDatabase(),
        //         $collection,
        //         ['metacode' => 'country']
        //     );
        // }
    }

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

    /**
     *
     */
    public function execute(OutputInterface $output = null)
    {
        $bulkData = [];

        $query = 'SELECT * FROM filoblu_refilo_country_continent as cc inner join filoblu_refilo_continent as c on c.continent_id = cc.continent_id;';

        $result = $this->resourceConnection->getConnection()->fetchAll($query);
        foreach ($result as $item) {
            $country = new stdClass();
            $country->_id = 'geocountry_' . $item['country_id'];

            $country->metadata = new stdClass();
            $country->metacode = 'country';
            $country->metadata->code = $item['country_id'];
            $country->metadata->label = $item['country_name'];
            $country->metadata->continent_id = (int)$item['continent_id'];
            $country->metadata->continent_name = $item['continent'];
            $country->metadata->position = (int)$item['position'];
            $country->metadata->regions = [];

            $query = "SELECT * FROM directory_country_region as cr WHERE country_id = '{$item['country_id']}'";
            $result_regions = $this->resourceConnection->getConnection()->fetchAll($query);
            if (count($result_regions)) {
                foreach ($result_regions as $result_region) {
                    $region = new stdClass();
                    $region->id = $result_region['region_id'];
                    $region->code = $result_region['code'];
                    $region->name = $result_region['default_name'];
                    $country->metadata->regions[] = $region;
                }
            }
            $bulkData[] = $country;
        }

        $this->write($bulkData);
    }

    /**
     * @param $bulkData
     */
    public function write($bulkData)
    {
        $projectIds = [$this->getDatabase()];

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

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