<?php

namespace Velis\Test;

use Building\Building;
use Generator;
use PHPUnit\Framework\TestCase;
use User\User;
use Velis\Bpm\Ticket\Ticket;
use Velis\Exception;
use Velis\Model\DataObject;

class DataObjectTest extends TestCase
{
    public function testInstance()
    {
        $nullObject = User::instance(0);
        $notNullObject = User::instance(1);
        $arrayObject = User::instance([1, 2, 3]);

        $this->assertNull($nullObject);
        $this->assertIsObject($notNullObject);
        $this->assertIsArray($arrayObject);
    }

    public function testTicketInstance()
    {
        $singleTicket = Ticket::instance(10);
        $arrayOfTickets = Ticket::instance([10]);
        $nullTicket = Ticket::instance(0);
        $emptyArrayOfTickets = Ticket::instance([0]);

        $this->assertIsObject($singleTicket);
        $this->assertIsArray($arrayOfTickets);
        $this->assertNull($nullTicket);
        $this->assertIsArray($emptyArrayOfTickets);
        $this->assertEmpty($emptyArrayOfTickets);
    }

    public function testMethodCall()
    {
        $foundBuildingObject = Building::instance(1);
        $notFoundBuildingObject = Building::instance(0);

        $this->assertNotNull($foundBuildingObject->getComplex()->id());
        //$this->assertNull($notFoundBuildingObject?->getComplex()?->id());
    }

    /**
     * @dataProvider getBoolDataProvider
     */
    public function testGetBoolExistingField(int|string|bool|null $value, ?bool $expectedResult): void
    {
        $instance = new User();
        $instance['is_active'] = $value;

        $this->assertEquals($expectedResult, $instance->getBool('is_active'));
    }

    public function getBoolDataProvider(): Generator
    {
        yield [1, true];
        yield [0, false];
        yield ['1', true];
        yield ['0', false];
        yield ['true', true];
        yield ['false', false];
        yield [null, null];
    }

    public function testGetBoolMissingField()
    {
        $instance = new User();

        $this->expectException(Exception::class);

        $instance->getBool('not_existing_field');
    }

    public function testPgDataToArray(): void
    {
        $pgNullArrayAsString = '{NULL}';
        $pgNotEmptyArrayAsArray = '{1,2,3}';
        $pgEmptyArrayAsString = '{}';

        $this->assertEquals([], DataObject::dataToArray($pgNullArrayAsString));
        $this->assertEquals([1, 2, 3], DataObject::dataToArray($pgNotEmptyArrayAsArray));
        $this->assertEquals([], DataObject::dataToArray($pgEmptyArrayAsString));
    }
}
