<?php

namespace App\Classes\Modules\Documents\ControllersLogic;

use App\Classes\Exceptions\AccessForbiddenException;
use App\Classes\Exceptions\RequestValidationException;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Documents\Standards\Rules\CanRenderDocument;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Tymon\JWTAuth\JWT;

class RenderDocumentLogic extends AbstractControllerLogic
{

    protected function notification(): array {
        return [
            'title' => '',
            'message' => ''
        ];
    }

    /** @var CanRenderDocument */
    private $canRenderDocument;

    /** @var JWT */
    private $manager;

    /**
     * RenderDocumentLogic constructor.
     * @param CanRenderDocument $canRenderDocument
     * @param JWT $manager
     */
    public function __construct(CanRenderDocument $canRenderDocument, JWT $manager)
    {
        $this->canRenderDocument = $canRenderDocument;
        $this->manager = $manager;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws AccessForbiddenException
     * @throws RequestValidationException
     * @throws ResourceNotFoundException
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function logic(Request $request) : JsonResponse
    {
        $file = $request->route('fileName');

        $this->canRenderDocument->passes();

        if(!Storage::disk('documents')->exists($file))
        {
            throw new ResourceNotFoundException();
        }

        return $this->response(['src' => explode('.', $file)[1] == 'pdf' ? chunk_split(base64_encode(Storage::disk('documents')->get($file))) : Storage::disk('documents')->get($file) ]);
    }
}