<?php
namespace Incoviba\Repository;

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

class Direccion extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Comuna $comunaRepository)
    {
        parent::__construct($connection);
        $this->setTable('direccion');
    }

    public function create(?array $data = null): Define\Model
    {
        $map = (new Implement\Repository\MapperParser(['calle', 'numero', 'extra']))
            ->register('comuna', (new Implement\Repository\Mapper())->setFunction(function($data) {
                return $this->comunaRepository->fetchById($data['comuna']);
            }));
        return $this->parseData(new Model\Direccion(), $data, $map);
    }
    public function save(Define\Model $model): Define\Model
    {
        $model->id = $this->saveNew(
            ['calle', 'numero', 'extra', 'comuna'],
            [$model->calle, $model->numero, $model->extra, $model->comuna->id]
        );
        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, ['calle', 'numero', 'extra', 'comuna'], $new_data);
    }

    /**
     * @param string $calle
     * @param int $numero
     * @return array
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByCalleAndNumero(string $calle, int $numero): array
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `calle` = ? AND `numero` = ?";
        return $this->fetchMany($query, [$calle, $numero]);
    }

    /**
     * @param string $calle
     * @param int $numero
     * @param string $extra
     * @param int $comuna_id
     * @return Model\Direccion
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByCalleAndNumeroAndExtraAndComuna(string $calle, int $numero, string $extra, int $comuna_id): Model\Direccion
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `calle` = ? AND `numero` = ? AND `extra` = ? AND `comuna` = ?";
        return $this->fetchOne($query, [$calle, $numero, $extra, $comuna_id]);
    }
}
