<?php

class InventoryLibTest extends PHPUnit_Framework_TestCase
{
    private $lib;

    public function __construct()
    {
        $this->lib = new InventoryLib();
    }

    public function testApplyFilter()
    {
        $data = [
            'input' => json_decode('{"filter" : {"Host name" : {"l" : "%mender%", "nil" : "%io%"}}}'),
            'result' => "WHERE values->>'Host name' LIKE '%mender%' AND values->>'Host name' NOT ILIKE '%io%'"
        ];
        $this->assertEquals($this->lib->applyFilter($data['input']), $data['result']);
    }

    public function testApplySorting()
    {
        $data = [
            [
                'input' => json_decode('{"sort":"Host name"}'),
                'result' => " ORDER BY values->>'Host name' ASC "
            ],
            [
                'input' => json_decode('{"sort":"-Host name"}'),
                'result' => " ORDER BY values->>'Host name' DESC "
            ],
            [
                'input' => '',
                'result' => ''
            ]
        ];
        foreach ($data as $d) {
            $this->assertEquals($this->lib->applySorting($d['input']), $d['result']);
        }
    }

    public function testApplySelect()
    {
        $data = [
            'input' => json_decode('{"select" : ["Host name", "OS type", "IPv4 addresses", "CFEngine version","Ports listening"]}'),
            'result' => ' values->>\'Host name\' AS "Host name",  values->>\'OS type\' AS "OS type",  cf_clearSlist(values->>\'IPv4 addresses\') AS "IPv4 addresses",  values->>\'CFEngine version\' AS "CFEngine version",  cf_clearSlist(values->>\'Ports listening\') AS "Ports listening"'
        ];
        $this->assertEquals($this->lib->applySelect($data['input']), $data['result']);

        $this->expectException(Exception::class);
        $this->lib->applySelect(json_decode('{"select" : 1111}'));
    }

    public function testException()
    {
        $this->expectException(Exception::class);
        $this->lib->applySelect(' ');
    }

    public function testMakeWhereCondition()
    {
        $data = [
            'input' => json_decode('{"filter" : {"CPU physical cores" : {"eq" : "2"}}}'),
            'result' => "WHERE cf_convertToNum(values->>'CPU physical cores') = cf_convertToNum('2')"
        ];

        $this->assertEquals($this->lib->applyFilter($data['input']), $data['result']);

        $this->expectException(Exception::class);
        $this->lib->applyFilter(json_decode('{"filter" : {"CPU physical cores" : {"notExistOperator" : "2"}}}'));
    }

    public function testGetLimit()
    {
        $this->assertEquals($this->lib->getLimit(), 1000);
        $this->assertEquals($this->lib->getLimit(-1), 1000);
        $this->assertEquals($this->lib->getLimit('not a number'), 1000);
        $this->assertEquals($this->lib->getLimit(10), 10);
        $this->assertEquals($this->lib->getLimit(999999), 10000);
        $this->assertEquals($this->lib->getLimit(100000000000000000), 10000);
    }

}
