<?php
namespace Incoviba\Repository;

use DateTimeImmutable;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;

class Login extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected User $userRepository)
    {
        parent::__construct($connection);
        $this->setTable('logins');
    }


    public function create(?array $data = null): Model\Login
    {
        $map = (new Implement\Repository\MapperParser(['selector', 'token']))
            ->register('user_id', (new Implement\Repository\Mapper())
                ->setProperty('user')
                ->setFunction(function($data) {
                    return $this->userRepository->fetchById($data['user_id']);
                }))
            ->register('time', new Implement\Repository\Mapper\DateTime('time', 'dateTime'))
            ->register('status', new Implement\Repository\Mapper\Boolean('status'));
        return $this->parseData(new Model\Login(), $data, $map);
    }

    public function save(Define\Model $model): Model\Login
    {
        $model->id = $this->saveNew(
            ['user_id', 'selector', 'token', 'time', 'status'],
            [$model->user->id, $model->selector, $model->token, $model->dateTime->format('Y-m-d H:i:s'), $model->status ? 1 : 0]);
        return $model;
    }

    public function edit(Define\Model $model, array $new_data): Model\Login
    {
        return $this->update($model, ['user_id', 'selector', 'token', 'time', 'status'], $new_data);
    }

    public function fetchByUser(int $user_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('user_id = ?');
        return $this->fetchMany($query, [$user_id]);
    }

    /**
     * @param int $user_id
     * @return Model\Login
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchActiveByUser(int $user_id): Model\Login
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('user_id = ? AND `status` = 1');
        return $this->fetchOne($query, [$user_id]);
    }
    public function fetchBySelectorAndToken(string $selector, string $token): Model\Login
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('selector = ? AND token = ?');
        return $this->fetchOne($query, [$selector, $token]);
    }
    public function fetchActiveBySelector(string $selector): Model\Login
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('selector = ? AND `status` = 1');
        return $this->fetchOne($query, [$selector]);
    }
}
