<?php
namespace Incoviba\Controller\API;

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

class Regiones
{
    use withRedis, withJson;

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