<?php
namespace Incoviba\Repository;

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

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

    public function create(?array $data = null): Model\Persona
    {
        $map = (new Implement\Repository\MapperParser(['rut', 'digito', 'nombres']))
            ->register('apellido_paterno', (new Implement\Repository\Mapper())->setProperty('apellidoPaterno'))
            ->register('apellido_materno', (new Implement\Repository\Mapper())->setProperty('apellidoMaterno'))
        ;
        return $this->parseData(new Model\Persona(), $data, $map);
    }
    public function save(Define\Model $model): Model\Persona
    {
        $this->saveNew(['rut', 'digito', 'nombres', 'apellido_paterno', 'apellido_materno'],
            [$model->rut, $model->digito, $model->nombres, $model->apellidoPaterno, $model->apellidoMaterno]);
        return $model;
    }

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

    public function filterData(array $data): array
    {
        return array_intersect_key($data, array_flip(['rut', 'digito', 'nombres', 'apellido_paterno', 'apellido_materno']));
    }

    protected function getKey(): string
    {
        return 'rut';
    }
}
