<?php


namespace CubiStore\Web\Controller;

use CubiStore\Web\Service\FDroidRepoService;
use Slim\Psr7\Response;

class Repo
{
    public function json(Response $response, FDroidRepoService $repoService)
    {
        $jsonArr = $repoService->createIndexV1Array();

        $response
            ->getBody()->write((string)json_encode($jsonArr));

        return $response
            ->withHeader('Content-Type', 'application/json');
    }

    public function jarJson(Response $response, FDroidRepoService $repoService)
    {
        $jsonArr = $repoService->createIndexV1Array();
        $jsonFile = json_encode($jsonArr);

        if ($jsonFile === false) {
            throw new \RuntimeException("Failed creating repo");
        }

        $jar = $repoService->createSigned('index-v1.json', $jsonFile);
        $response->getBody()->write($jar);

        return $response
            ->withHeader('Content-Type', 'application/x-jar')
            ->withHeader('ETag', (string)time());
    }
}
