<?php


class ApiVariablesDictionaryModelTest extends BaseTestClass
{
    private $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new VariablesDictionaryModel();
        $this->loadPostgresqlCFDBFixtures();
    }

    public function testUpdateCustomVariables()
    {
        $this->assertTrue($this->model->updateCustomVariables());
    }

    public function testGetAll()
    {
        $allItems = $this->model->getAll();
        $count = $this->db->query('SELECT * FROM variables_dictionary')->rowCount();
        $this->assertEquals($count, count($allItems));
    }

    public function testGetById()
    {
        $sql = "SELECT * FROM variables_dictionary WHERE id = 1 LIMIT 1";
        $item = $this->db->query($sql)->fetch(PDO::FETCH_ASSOC);
        $itemFromModel = $this->model->getById(1);
        $this->assertSame($item, $itemFromModel);
    }

    public function testUpdate()
    {
        $this->assertTrue($this->model->updateCustomVariables());
        $updateData = [
            'type' => 'int',
            'attribute_name' => 'new name'
        ];

        $sql = 'SELECT * FROM variables_dictionary WHERE readonly = 0 LIMIT 1';
        $item = $this->db->query($sql)->fetch(PDO::FETCH_ASSOC);
        $this->model->update($item['id'], (object) $updateData);
        $updatedItem = $this->model->getById($item['id']);
        $this->assertEquals($updatedItem['type'], $updateData['type']);
        $this->assertNotEquals($updatedItem['attribute_name'], $updateData['attribute_name']);
    }

    public function testValidate()
    {
        $dataToValidate = [
            'error' => ['type' => 'wrongType', 'convert_function' => 'wrong_function'],
            'success' => ['type' => 'int', 'convert_function' => 'cf_clearSlist']
        ];

        $this->assertTrue($this->model->validate((object) $dataToValidate['success']));
        $this->assertFalse($this->model->validate((object) $dataToValidate['error']));
    }

}
