<?php
namespace Incoviba\Service;

use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;

class Persona extends Ideal\Service
{
    public function __construct(LoggerInterface $logger, protected Repository\Persona $personaRepository,
                                protected Repository\DatosPersona $datosPersonaRepository)
    {
        parent::__construct($logger);
    }

    public function getByRut(int $rut): Model\Persona
    {
        return $this->process($this->personaRepository->fetchByRut($rut));
    }
    public function add(array $data): Model\Persona
    {
        try {
            $persona = $this->personaRepository->fetchByRut($data['rut']);
        } catch (Implement\Exception\EmptyResult) {
            $persona = $this->personaRepository->create($data);
            $persona = $this->personaRepository->save($persona);
        }
        if (isset($data['email']) or isset($data['telefono'])) {
            $datosData = ['persona_rut' => $persona->rut];
            if (isset($data['email'])) {
                $datosData['email'] = $data['email'];
            }
            if (isset($data['telefono'])) {
                $datosData['telefono'] = $data['telefono'];
            }
            try {
                $datos = $this->datosPersonaRepository->fetchByPersona($persona->rut);
                $this->datosPersonaRepository->edit($datos, $data);
            } catch (Implement\Exception\EmptyResult) {
                $datos = $this->datosPersonaRepository->create($datosData);
                $this->datosPersonaRepository->save($datos);
            }
        }
        return $this->process($persona);
    }

    protected function process(Model\Persona $persona): Model\Persona
    {
        $persona->addFactory('datos', (new Implement\Repository\Factory())
            ->setCallable([$this->datosPersonaRepository, 'fetchByPersona'])
            ->setArgs(['persona_rut' => $persona->rut]));
        return $persona;
    }
}
