<?php

namespace KupShop\UserBundle\Test;

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\UserBundle\Util\UserImporter;
use Query\Operator;

class UserImportTest extends \DatabaseTestCase
{
    public function getDataSet()
    {
        return $this->getJsonDataSetFromFile();
    }

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

    protected function setEnvironment()
    {
        $this->userImporter = ServiceContainer::getService(UserImporter::class);
    }

    public function testImportInsertUser()
    {
        $this->setEnvironment();
        $xmlResponse = file_get_contents(__DIR__.'/UserImportTest.xml');

        // BEFORE ACTION
        $insertBefore = $this->getData('customupdate@wpj.cz');
        $this->assertCount(0, $insertBefore);

        $this->userImporter->importUsers($xmlResponse);

        // AFTER ACTION
        $insertAfter = $this->getData('customupdate@wpj.cz');
        $this->assertCount(1, $insertAfter);
    }

    public function testImportUpdateUser()
    {
        $this->setEnvironment();
        $xmlResponse = file_get_contents(__DIR__.'/UserImportTest.xml');

        // BEFORE ACTION
        $updateBefore = $this->getData('wpj@wpj.cz');
        $this->assertEquals('Test', $updateBefore[0]['name']);
        $this->assertEquals('Wpj', $updateBefore[0]['surname']);

        $this->userImporter->importUsers($xmlResponse);

        // AFTER ACTION
        $updateAfter = $this->getData('wpj@wpj.cz');
        $this->assertEquals('TestPoImportu', $updateAfter[0]['name']);
        $this->assertEquals('WpjPoImportu', $updateAfter[0]['surname']);
    }

    private function getData($email, $selector = '*')
    {
        return sqlQueryBuilder()
            ->select($selector)
            ->from('users')
            ->andWhere(Operator::equals(['email' => $email]))
            ->groupBy('email')
            ->execute()->fetchAll();
    }
}
