<?php
namespace Incoviba\Repository;

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

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

    public function create(?array $data = null): Define\Model
    {
        $map = (new Implement\Repository\MapperParser(['name', 'password']))
            ->register('enabled', new Implement\Repository\Mapper\Boolean('enabled'));
        return $this->parseData(new Model\User(), $data, $map);
    }

    public function save(Define\Model $model): Define\Model
    {
        $model->id = $this->saveNew(['name', 'password', 'enabled'], [$model->name, $model->password, $model->enabled ? 1 : 0]);
        return $model;
    }

    /**
     * @param Define\Model $model
     * @param array $new_data
     * @return Define\Model
     * @throws Implement\Exception\EmptyResult
     */
    public function edit(Define\Model $model, array $new_data): Define\Model
    {
        return $this->update($model, ['name', 'password', 'enabled'], $new_data);
    }

    /**
     * @param string $name
     * @return Model\User
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByName(string $name): Model\User
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `name` = ?";
        return $this->fetchOne($query, [$name]);
    }
}
