<?php
namespace Incoviba\Controller;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Repository;
use Incoviba\Service;

class Inmobiliarias
{
    use withRedis;

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view,
                             Service\Redis $redisService, Repository\Inmobiliaria $inmobiliariaRepository): ResponseInterface
    {
        $redisKey = 'inmobiliarias';
        $inmobiliarias = [];
        try {
            $inmobiliarias = array_map(function($row) use ($inmobiliariaRepository) {
                return $inmobiliariaRepository->load($row);
            }, $this->fetchRedis($redisService, $redisKey, true));
        } catch (EmptyRedis) {
            try {
                $inmobiliarias = $inmobiliariaRepository->fetchAll();
                $this->saveRedis($redisService, $redisKey, $inmobiliarias);
            } catch (EmptyResult) {}
        }
        return $view->render($response, 'inmobiliarias.list', compact('inmobiliarias'));
    }
    public function show(ServerRequestInterface $request, ResponseInterface $response, View $view,
                         Service\Redis $redisService, Repository\Inmobiliaria $inmobiliariaRepository, int $inmobiliaria_rut): ResponseInterface
    {
        $redisKey = "inmobiliaria:{$inmobiliaria_rut}";
        try {
            $inmobiliaria = $inmobiliariaRepository->load((array) $this->fetchRedis($redisService, $redisKey));
        } catch (EmptyResult) {
            $inmobiliaria = $inmobiliariaRepository->fetchById($inmobiliaria_rut);
            $this->saveRedis($redisService, $redisKey, $inmobiliaria);
        }
        return $view->render($response, 'inmobiliaria.show', compact('inmobiliaria'));
    }
}
