<?php

namespace KupShop\OrderingBundle\Tests\Order;

use KupShop\OrderingBundle\Util\Order\OrderImporter;
use Query\Operator;

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

    /**
     * @var OrderImporter
     */
    protected $orderImporter;

    protected function setEnvironment()
    {
        $this->orderImporter = $this->get(OrderImporter::class);
    }

    public function testOrderImporter()
    {
        $this->setEnvironment();

        $orderCount = $this->selectFromOrderDB('COUNT(id)', 'orders');
        $orderItemCount = $this->selectFromOrderDB('COUNT(id)', 'order_items');

        $this->assertEquals('0', $orderCount['COUNT(id)']);
        $this->assertEquals('0', $orderItemCount['COUNT(id)']);

        // INSERT
        $xml = file_get_contents(__DIR__.'/OrderImporterTest.xml');
        $this->orderImporter->importOrders($xml, true);

        $newOrderCount = $this->selectFromOrderDB('COUNT(id)', 'orders');
        $newOrderItemCount = $this->selectFromOrderDB('COUNT(id)', 'order_items');

        $orderData = $this->selectFromOrderDB('*', 'orders', ['order_no' => 'O12345']);
        $orderItemData = $this->selectFromOrderDB('*', 'order_items', ['descr' => 'Bastoncini - dřívka na nanuky 500 ks']);

        $this->assertEquals('1', $newOrderCount['COUNT(id)']);
        $this->assertEquals('2', $newOrderItemCount['COUNT(id)']);

        $this->assertEquals('wpj s.r.o.', $orderData['invoice_firm']);
        $this->assertEquals('test@wpj.cz', $orderData['invoice_email']);
        $this->assertEquals('2', $orderItemData['pieces']);

        // UPDATE
        $newXml = str_replace('1200', '98', $xml);
        $this->orderImporter->importOrders($newXml, true);

        $updatePrice = $this->selectFromOrderDB('*', 'order_items', ['descr' => 'Bastoncini - dřívka na nanuky 500 ks']);

        $this->assertEquals('98.0000', $updatePrice['total_price']);
    }

    private function selectFromOrderDB($selector, $table, $where = null)
    {
        $qb = sqlQueryBuilder()
            ->select($selector)
            ->from($table);
        if ($where) {
            $qb->andWhere(Operator::equals($where));
        }

        return $qb->execute()->fetch();
    }
}
