<?php
namespace Incoviba\Controller\API;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\withRedis;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;

class Provincias
{
    use withRedis, withJson;

    public function comunas(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
                            Repository\Comuna $comunaRepository, int $provincia_id): ResponseInterface
    {
        $output = [
            'provincia_id' => $provincia_id,
            'comunas' => []
        ];
        $redisKey = "comunas:provincia:{$provincia_id}";
        try {
            $output['comunas'] = $this->fetchRedis($redisService, $redisKey);
        } catch (EmptyRedis) {
            try {
                $comunas = $comunaRepository->fetchByProvincia($provincia_id);
                usort($comunas, function(Model\Comuna $a, Model\Comuna $b) {
                    return strcmp($a->descripcion, $b->descripcion);
                });
                $output['comunas'] = $comunas;
                $this->saveRedis($redisService, $redisKey, $comunas, 60 * 60 * 24 * 30);
            } catch (EmptyResult) {}
        }
        return $this->withJson($response, $output);
    }
}
