<?php

namespace Sitecake;

use Sitecake\Http\Session;

class SessionManager
{
    const SESSION_TIMEOUT = 10000;

    /** @var Session */
    protected $session;

    /** @var FileLock */
    protected $fileLock;

    public function __construct(Session $session, FileLock $fileLock)
    {
        $this->session  = $session;
        $this->fileLock = $fileLock;
    }

    public function startSession(): void
    {
        if (!$this->sessionStarted()) {
            $this->session->set('loggedin', true);
            $this->fileLock->set('login', self::SESSION_TIMEOUT);
            Sitecake::eventBus()->dispatch('Sitecake.editSessionStart');
        }
    }

    public function sessionStarted(): bool
    {
        return $this->session->has('loggedin');
    }

    public function sessionExists(): bool
    {
        return $this->fileLock->exists('login');
    }

    public function terminate(): void
    {
        $this->session->invalidate(0);
        $this->fileLock->remove('login');
        Sitecake::eventBus()->dispatch('Sitecake.editSessionEnd');
    }

    public function refresh(): void
    {
        if ($this->sessionStarted()) {
            $this->fileLock->set('login', self::SESSION_TIMEOUT);
            Sitecake::eventBus()->dispatch('Sitecake.editSessionRenew');
        }
    }
}
