<?php

/**
 * Created by PhpStorm.
 * User: filip
 * Date: 5/27/16
 * Time: 1:39 PM.
 */

namespace FilterTest;

use Query\Operator;

class FilterParamsTest extends \DatabaseTestCase
{
    /** @var \FilterParams */
    private $filterParams;

    public function setUp(): void
    {
        parent::setUp();

        $this->filterParams = new \FilterParams();
        $this->filterParams->setSections([3]);
    }

    public function testGetSpecWithoutParametersAndsAllSpecs()
    {
        $this->filterParams->setPriceRange(1000, 5000);

        $count = sqlQueryBuilder()->select('*')->fromProducts()->where($this->filterParams->getSpec())->execute()->rowCount();
        $this->assertSame(2, $count);
    }

    public function testAddSpec()
    {
        $this->filterParams->andSpec(Operator::between('price', new \Range(1000, 5000)));

        $count = sqlQueryBuilder()->select('*')->fromProducts()->where($this->filterParams->getSpec())->execute()->rowCount();
        $this->assertSame(2, $count);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSetResultEntityThrows()
    {
        $this->filterParams->setResultEntity('invalid');
    }

    public function testGetResultEntityDefault()
    {
        $this->assertSame(\FilterParams::ENTITY_PRODUCT, $this->filterParams->getResultEntity());
    }

    public function testSetAndGetResultEntity()
    {
        $this->filterParams->setResultEntity(\FilterParams::ENTITY_VARIATION);
        $this->assertSame(\FilterParams::ENTITY_VARIATION, $this->filterParams->getResultEntity());
    }

    public function testConvenienceMethods()
    {
        $this->assertTrue($this->filterParams->resultEntityIsProduct());
        $this->filterParams->setResultEntity(\FilterParams::ENTITY_VARIATION);
        $this->assertTrue($this->filterParams->resultEntityIsVariation());
    }

    /**
     * @dataProvider dataProvider_testGetInStore
     */
    public function testGetInStoreReturnsDomainDefaultIfNotOverridenBySetInStore($setting, $supplierStoreModuleExists, $expectedResult)
    {
        \Settings::getDefault()->loadFromArray(['prod_show_not_in_store' => $setting], true);
        global $cfg;
        $cfg['Modules']['products_suppliers'] = $supplierStoreModuleExists;

        $result = $this->filterParams->getInStore();

        $this->assertSame($expectedResult, $result);
    }

    public function dataProvider_testGetInStore()
    {
        return [
            'Show not in store' => ['Y', null, null],
            'Show in store' => ['N', false, \Filter::IN_STORE],
            'Show in store supplier' => ['N', true, \Filter::IN_STORE_SUPPLIER],
        ];
    }

    public function testGetInStoreReturnsValueSetBySetInStore()
    {
        $this->filterParams->setInStore('Wrong');
        $this->assertSame('Wrong', $this->filterParams->getInStore());
    }
}
