<?php

namespace KupShop\PohodaBundle\Tests\Users\Import;

use KupShop\DevelopmentBundle\Util\Tests\LoggerTestTrait;
use KupShop\PohodaBundle\Tests\TestUtilHelper;
use KupShop\PohodaBundle\Utils\Importers\UsersImporter;
use KupShop\PohodaBundle\Utils\Tools\TransformHelper;
use KupShop\UserBundle\Util\UserImporter;
use Query\Operator;

class ImportUserTest extends \DatabaseTestCase
{
    use LoggerTestTrait;
    use TestUtilHelper;

    public function getDataSet()
    {
        return $this->getJsonDataSetFromFile();
    }

    /**
     * @var TransformHelper
     */
    protected $transformHelper;

    /**
     * @var UserImporter
     */
    protected $userImporter;

    protected function setEnvironment()
    {
        $this->userImporter = $this->get(UsersImporter::class);
        $this->transformHelper = $this->get(TransformHelper::class);
        $this->getLogger();
    }

    public function testTransformUsersIn()
    {
        $resultXML = $this->transformXML('users', 'users');
        $this->assertXmlStringEqualsXmlFile(__DIR__.'/usersInResult.xml', $resultXML);
    }

    public function testImportInsertUsers()
    {
        // TRANSFORM XML
        $resultXML = $this->transformXML('users', 'users');

        // IMPORT USERS
        $this->userImporter->importUsers($resultXML);

        // EXPECTED NEW USERS
        $insertedEmails = [
            'info@stormware.cz',
            'obchod@boll.cz',
            'sklad@email.cz',
        ];

        // GET EXPECTED USERS
        $users = sqlFetchAll(sqlQueryBuilder()
            ->select('*')
            ->from('users')
            ->andWhere(Operator::inStringArray($insertedEmails, 'email'))
            ->execute(), 'email');

        // TESTING DATA
        $this->assertCount(3, $users);
        $this->assertEquals('Stormware s.r.o.', $users['info@stormware.cz']['firm']);
        $this->assertEquals('Praha', $users['sklad@email.cz']['city']);
        $this->assertEquals('Petrohradská 216/3', $users['obchod@boll.cz']['street']);

        // TEST LOG
        $testHandler = $this->getTestHandler();
        $this->assertEquals(true, $testHandler->hasNoticeThatContains('POHODA RESPONSE: Users Import'));
        foreach ($testHandler->getRecords() as $record) {
            if ($record['message'] == 'POHODA RESPONSE: Users Import') {
                if ($users[$record['context']['data']->EMAIL->__toString()] ?? false) {
                    $this->assertEquals($users[$record['context']['data']->EMAIL->__toString()]['firm'], $record['context']['data']->INVOICE->COMPANY);
                }
            }
        }
    }

    public function testImportUpdateUsers()
    {
        // TRANSFORM XML
        $resultXML = $this->transformXML('users', 'users');

        // EXPECTED EMAIL UPDATE
        $updateEmail = 'wpj@wpj.cz';

        // TEST BEFORE IMPORT
        $beforeUpdateData = $this->getDatabaseData($updateEmail);
        $this->assertEquals('Fügnerova 1288', $beforeUpdateData['wpj@wpj.cz']['street']);

        // IMPORT USERS
        $this->userImporter->importUsers($resultXML);

        // GET UPDATES
        $updateData = $this->getDatabaseData($updateEmail);

        // TESTING DATA
        $this->assertEquals('New WPJ t. e. s. t.', $updateData['wpj@wpj.cz']['firm']);
        $this->assertEquals('U WPJ, test 123', $updateData['wpj@wpj.cz']['street']);
    }

    public function getDatabaseData($updateEmail)
    {
        return sqlFetchAll(sqlQueryBuilder()
            ->select('*')
            ->from('users')
            ->andWhere(Operator::equals(['email' => $updateEmail]))
            ->execute(), 'email');
    }

    public function transformXML($prefixInXML, $prefixTransformXSL)
    {
        $this->setEnvironment();
        $this->prepareMServer();
        $xmlResponse = file_get_contents(__DIR__.'/'.$prefixInXML.'InResponse.xml');

        return $this->transformHelper->baseTransform($xmlResponse, $this->transformHelper->loadXslt($prefixTransformXSL.'In.xsl'));
    }
}
