<?php
/**
 * Created by PhpStorm.
 * User: eater
 * Date: 4/2/16
 * Time: 8:48 PM
 */

namespace Eater\Glim\Handler;

use Aura\Session\Segment;
use Eater\Glim\Model\UserQuery;
use Eater\Glim\Model\User;
use Eater\Glim\Service\TwigVars;

class Session extends Main
{
    /**
     * @var bool
     */
    protected $shouldHaveUser = true;

    /**
     * @var bool
     */
    protected $shouldHaveSuperuser = false;

    /**
     * @var User
     */
    protected $user;

    /**
     * @return User
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * @param User $user
     */
    public function setUser($user)
    {
        $this->user = $user;
    }

    
    public function beforeHandle()
    {
        if (!UserQuery::create()->findOne()) {
            return $this->redirect('/install');
        }

        /* @var \Aura\Session\Session */
        $session = $this->get('session');
        /** @var TwigVars $twigVar */
        $twigVar = $this->get('twig-vars');
        /** @var Segment $segment */
        $segment = $session->getSegment('main');
        /** @var User $user */
        $userId = $segment->get('userId');

        $user = UserQuery::create()->findOneById($userId);

        $twigVar->def('user', $user);

        $this->setUser($user);

        if ($user === null && ($this->shouldHaveUser || $this->shouldHaveSuperuser)) {
            $segment->set('afterLogin', $this->getRequest()->getUri());
            return $this->redirect('/login');
        } elseif ($this->shouldHaveSuperuser && !$user->getSuperuser()) {
            return $this->redirect('/panel');
        }
    }
}