<?php
namespace Incoviba\Controller;

use Incoviba\Common\Implement\Exception\EmptyResult;
use PDOException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Ideal\Controller;
use Incoviba\Repository;
use Incoviba\Service;

class Login extends Controller
{
    public function form(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Login $service): ResponseInterface
    {
        if ($service->isIn()) {
            return $response->withStatus(302)->withHeader('Location', $view->get('urls')->base);
        }
        return $view->render($response, 'login.form');
    }
    public function login(ServerRequestInterface $request, ResponseInterface $response, Repository\User $userRepository, Service\Login $service): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = [
            'name' => $body['name'],
            'login' => false
        ];

        try {
            $user = $userRepository->fetchByName($body['name']);
            if ($service->validateUser($user, $body['password'])) {
                $output['login'] = $service->login($user);
            }
        } catch (EmptyResult) {}
        $response->getBody()->write(json_encode($output));
        return $response->withHeader('Content-Type', 'application/json');
    }
    public function logout(ServerRequestInterface $request, ResponseInterface $response, Repository\Login $loginRepository, Service\Login $service): ResponseInterface
    {
        $output = [
            'name' => '',
            'logout' => false
        ];
        try {
            $user = $service->getUser();
            $output = [
                'name' => $user->name,
                'logout' => $service->logout($user)
            ];
        } catch (PDOException) {}
        $response->getBody()->write(json_encode($output));
        return $response->withHeader('Content-Type', 'application/json');
    }
}
