<?php
namespace Incoviba\Controller;

use Incoviba\Common\Implement\Exception\EmptyResult;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Repository;
use Incoviba\Model;

class Direcciones
{
    public function comunas(ServerRequestInterface $request, ResponseInterface $response, Repository\Provincia $provinciaRepository, Repository\Comuna $comunaRepository, int $region_id) : ResponseInterface
    {
        $temp_provincias = $provinciaRepository->fetchByRegion($region_id);
        $comunas = [];
        foreach($temp_provincias as $provincia) {
            $temp_comunas = $comunaRepository->fetchByProvincia($provincia->id);
            $comunas = array_merge($comunas, $temp_comunas);
        }
        usort($comunas, function(Model\Comuna $a, Model\Comuna $b) {
            return strcoll($a->descripcion, $b->descripcion);
        });
        $response->getBody()->write(json_encode(['comunas' => $comunas, 'total' => count($comunas)]));
        return $response->withHeader('Content-Type', 'application/json');
    }
    public function findComunas(ServerRequestInterface $request, ResponseInterface $response, Repository\Comuna $comunaRepository): ResponseInterface
    {
        $body = $request->getBody();
        $json = json_decode($body->getContents());
        $output = ['total' => 0];
        try {
            $comunas = $comunaRepository->fetchByDireccion($json->direccion);
            $output['comunas'] = $comunas;
            $output['total'] = count($comunas);
        } catch (EmptyResult) {}
        $response->getBody()->write(json_encode($output));
        return $response->withHeader('Content-Type', 'application/json');
    }
}
