<?php

namespace External\CykloSpecialityBundle\Resources\script;

use External\CykloSpecialityBundle\Import\ImportData;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\System\PathFinder;
use Query\Operator;

class ImportDataScript extends Script
{
    protected static $name = 'Import Dat';
    protected static $defaultParameters = [
        'importUsers' => [
            'run' => false,
            'clearOld' => false,
            'source' => [
                'yaf18mcb_customers.xml',
            ],
        ],
        'importOrders' => [
            'run' => false,
            'clearOld' => false,
            'source' => [
                'yaf18mcb_orders.xml',
            ],
        ],
        'importProductsRewrite' => [
            'run' => false,
            'clearOld' => false,
            'source' => [
                'yaf18mcb_products.xml',
            ],
        ],
    ];

    protected ImportData $importData;

    public function __construct()
    {
        $this->importData = ServiceContainer::getService(ImportData::class);
    }

    protected function run(array $arguments): void
    {
        ini_set('max_execution_time', 60 * 60 * 24); // 24 hours
        ini_set('memory_limit', '2048M');
        $this->log('Importing data...');

        $this->importData->setWriteLineCallback(
            function ($str) {
                $this->log($str);
            }
        );

        foreach ($arguments as $name => $values) {
            $this->log($name);
            if (is_array($values) && $values['run']) {
                $this->{$name}($values);
            } else {
                if (!is_array($values) && $values) {
                    $this->{$name}();
                }
            }
            $this->log($name.' finished');
        }
        echo '<input type="button" value="Back" onclick="window.history.back()" />';
    }

    private function importUsers(array $arguments): void
    {
        $this->log('Importing users');

        if ($arguments['clearOld'] ?? false) {
            sqlQueryBuilder()->delete('users')->andWhere('JSON_VALUE(custom_data, "$.imported") = true')->execute();
            $this->log('Imported users deleted');
        }

        $this->loadXml(
            $arguments['source'],
            function ($xml) {
                $this->importData->importUsers($xml);
            }
        );

        $this->log('Users imported');
    }

    private function importOrders(array $arguments): void
    {
        $this->log('Importing orders');

        if ($arguments['clearOld'] ?? false) {
            sqlQueryBuilder()->delete('orders')->andWhere(Operator::equals(['source' => 'import']))->execute();
            $this->log('Imported orders deleted');
        }

        $this->loadXml(
            $arguments['source'],
            function ($xml) {
                $this->importData->importOrders($xml);
            }
        );

        $this->log('Orders imported');
    }

    private function importProductsRewrite(array $arguments): void
    {
        $this->log('Importing productsRewrite');

        if ($arguments['clearOld'] ?? false) {
            sqlQueryBuilder()->delete('rewrite')->andWhere(Operator::inIntArray([0, 6], 'type'))->execute();
            $this->log('Products rewrite deleted');
        }

        $this->loadXml(
            $arguments['source'],
            function ($xml) {
                $this->importData->importProductsRewrite($xml);
            }
        );

        $this->log('Product rewrite imported');
    }

    private function loadXml($source, callable $callback): void
    {
        foreach ($source as $file) {
            $pathData = (new PathFinder())->getDataDir().'files/'.$file;

            if (!$xml = simplexml_load_file($pathData)) {
                $xml = simplexml_load_file($file);
            }

            if ($xml) {
                $this->log('Importing file: '.$file);
                $callback($xml);
            } else {
                $this->log('Products file not found or could not be loaded: '.$file);
            }
        }
    }
}

return ImportDataScript::class;
