<?php

namespace App\Model;


use App\Model\Exceptions\Db\RecordNotFoundException;
use App\Model\Facades\UserFacade;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Nette\Security\IAuthenticator;
use Nette\Security\IUserStorage;
use Nette\Security\User as NetteUser;

class User extends NetteUser
{
    /** @var UserFacade */
    protected $userFacade;

    public function __construct(IUserStorage $storage, IAuthenticator $authenticator = NULL, Permission $authorizator = NULL, UserFacade $userFacade)
    {
        parent::__construct($storage, $authenticator, $authorizator);

        $this->userFacade = $userFacade;
        $this->initializeUserData();

        if ($this->isLoggedIn()) {
            $authorizator->setLoggedInUserId($this->id);
        }
    }

    public function login($id = NULL, $password = NULL)
    {
        parent::login($id, $password);

        $this->initializeUserData();
    }

    protected function initializeUserData()
    {
        if($this->isLoggedIn()) {
            try {
                $roles = array();
                $userEntity = $this->userFacade->getUserReader()->findUserById($this->getId());
                $this->userFacade->getUserAccountWriter()->updateLastOnline($userEntity);
                foreach ($userEntity->getRoles() as $role) {
                    $roles[$role->getId()] = $role->getName();
                }
                $this->getIdentity()->setRoles($roles);

                return;

            } catch (TableNotFoundException $e) {
                $this->logout(true);
            } catch (RecordNotFoundException $e) {
                $this->logout(true);
            }
        }
    }

    // todo: remove this method
    public function getUserEntity()
    {
        if ($this->isLoggedIn()) {
            return $this->userFacade->getUserReader()->findUserById($this->getId());
        }

        return new class
        {
            public function getNickname()
            {
                return 'guest';
            }
        };
    }
}