<?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 Direcciones
{
    use withRedis, withJson;

    public function get(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
                        Repository\Direccion $direccionRepository, int $direccion_id): ResponseInterface
    {
        $output = ['direccion_id' => $direccion_id, 'direccion' => null];
        $redisKey = "direcciones:{$direccion_id}";
        try {
            $direccion = $this->fetchRedis($redisService, $redisKey);
            $output['direccion'] = $direccion;
        } catch (EmptyRedis) {
            try {
                $direccion = $direccionRepository->fetchById($direccion_id);
                $output['direccion'] = $direccion;
                $this->saveRedis($redisService, $redisKey, $direccion, 60 * 60 * 24 * 30);
            } catch (EmptyResult) {}
        }

        return $this->withJson($response, $output);
    }
    public function comunas(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
                            Repository\Region $regionRepository, Repository\Comuna $comunaRepository,
                            int $region_id) : ResponseInterface
    {
        $output = ['total' => 0, 'comunas' => []];
        $redisKey = "comunas:region:{$region_id}";

        try {
            $output['comunas'] = $this->fetchRedis($redisService, $redisKey);
            $output['total'] = count($output['comunas']);
        } catch (EmptyRedis) {
            $regionKey = "regiones:{$region_id}";
            try {
                $region = $this->fetchRedis($redisService, $regionKey);
            } catch (EmptyRedis) {
                $region = $regionRepository->fetchById($region_id);
                $this->saveRedis($redisService, $regionKey, $region, 60 * 60 * 24 * 30);
            }
            $comunas = $comunaRepository->fetchByRegion($region->id);
            usort($comunas, function(Model\Comuna $a, Model\Comuna $b) {
                return strcoll($a->descripcion, $b->descripcion);
            });
            $output = ['comunas' => $comunas, 'total' => count($comunas)];
            $this->saveRedis($redisService, $redisKey, $comunas, 60 * 60 * 24 * 30);
            /*$provinciaKey = 'provincias';
            try {
                $temp_provincias = $this->fetchRedis($redisService, $provinciaKey);
            } catch (EmptyRedis) {
                $temp_provincias = $provinciaRepository->fetchByRegion($region_id);
                $this->saveRedis($redisService, $provinciaKey, $temp_provincias, 60 * 60 * 24 * 30);
            }
            $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);
            });
            $output = ['comunas' => $comunas, 'total' => count($comunas)];
            $this->saveRedis($redisService, $redisKey, $comunas, 60 * 60 * 24 * 30);*/
        }
        return $this->withJson($response, $output);
    }
    public function findComunas(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
                                Repository\Comuna $comunaRepository): ResponseInterface
    {
        $body = $request->getBody();
        $json = json_decode($body->getContents());
        $output = ['input' => $json, 'total' => 0, 'comunas' => []];
        $redisKey = "direcciones:{$json->direccion}:comuna";
        try {
            $output['comunas'] = $this->fetchRedis($redisService, $redisKey);
        } catch (EmptyRedis) {
            try {
                $comunas = $comunaRepository->fetchByDireccion($json->direccion);
                $output['comunas'] = $comunas;
                $output['total'] = count($comunas);
                $this->saveRedis($redisService, $redisKey, $comunas);
            } catch (EmptyResult) {}
        }
        return $this->withJson($response, $output);
    }

    public function edit(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
                         Repository\Direccion $direccionRepository, int $direccion_id): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = ['direccion_id' => $direccion_id, 'input' => $body, 'direccion' => [], 'success' => false];
        $redisKey = "direcciones:{$direccion_id}";
        try {
            $direccion = $direccionRepository->fetchById($direccion_id);
            $filteredData = $direccionRepository->filterData($body);
            $output['direccion'] = $direccionRepository->edit($direccion, $filteredData);
            $output['success'] = true;
            $this->saveRedis($redisService, $redisKey, $output['direccion'], 60 * 60 * 24 * 30);
        } catch (EmptyResult) {}

        return $this->withJson($response, $output);
    }
}
