<?php

namespace Velis\Test\App;

use PHPUnit\Framework\TestCase;
use ReflectionClass;
use Velis\App;
use Velis\App\User;
use Velis\Lang;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
class UserTest extends TestCase
{
    public static $settings = [
        'key' => 'value',
    ];

    /**
     * @param User   $user
     * @param string $language
     * @param string $expectedLocale
     *
     * @dataProvider provideTestDataForGetLocaleMethod
     */
    public function testGetLocale(User $user, $language, $expectedLocale)
    {
        Lang::switchLanguage($language, false);

        $actualLocale = $user->getLocale();

        $this->assertEquals($expectedLocale, $actualLocale);
    }

    public function provideTestDataForGetLocaleMethod()
    {
        $userPl = new User([
            'locale' => 'pl_PL',
        ]);

        $userCa = new User([
            'locale' => 'en_CA',
            'country_id' => 'CA',
        ]);

        return [
            [$userPl, 'pl', 'pl_PL'],
            [$userPl, 'en', 'en_US'],
            [$userCa, 'en', 'en_CA'],
            [$userCa, 'fr', 'fr_CA'],
            [$userCa, 'pl', 'pl_PL'],
        ];
    }

    /**
     * @param $settingKey
     * @param $expectedResult
     *
     * @dataProvider provideTestDataForSettingsMethod
     * @runInSeparateProcess
     */
    public function testSettings($settingKey, $expectedResult)
    {
        App::$session = App::$di['session'];
        App::$session->settings = self::$settings;
        $user = new User();

        $actualResult = $user->settings($settingKey);

        $this->assertEquals($expectedResult, $actualResult);
    }

    public function provideTestDataForSettingsMethod()
    {
        return [
            [null, self::$settings],
            ['key', 'value'],
        ];
    }

    public function testHasAnyPrivAccessGranted()
    {
        $module = 'Building';
        $acro = 'Ticket';

        $user = new User();

        $reflectionClass = new ReflectionClass($user);
        $reflectionProperty = $reflectionClass->getProperty('_privs');
        $reflectionProperty->setValue($user, [$module => [$acro]]);

        $result = $user->hasAnyPriv([
            [$module, $acro],
            ['NotPermittedModule', 'NotPermittedAcro'],
        ]);

        $this->assertTrue($result);
    }

    public function testHasAnyPrivAccessDenied()
    {
        $module = 'Building';
        $acro = 'Ticket';

        $user = new User();

        $reflectionClass = new ReflectionClass($user);
        $reflectionProperty = $reflectionClass->getProperty('_privs');
        $reflectionProperty->setValue($user, [$module => [$acro]]);

        $result = $user->hasAnyPriv([
            ['NotPermittedModule', 'NotPermittedAcro'],
        ]);

        $this->assertFalse($result);
    }
}
