<?php

namespace apexl\Io\modules\file\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\includes\System;
use apexl\Io\includes\Utils;
use apexl\Io\modules\file\entities\fileEntity;
use apexl\Io\modules\file\services\File;
use apexl\Io\modules\user\services\currentUser;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class fileController extends Controller
{
    protected $currentUser;
    protected $file;

    public function __construct(currentUser $currentUser, File $file)
    {
        parent::__construct();
        $this->file = $file;
        $this->currentUser = currentUser::getCurrentUser();
    }

    /**
     * Generic file store method. Returns file entity data
     * @param Request $request
     * @param Response $response
     * @throws \Exception
     * @return Response
     */
    public function files(Request $request, Response $response)
    {
        $fileEntity = $this->file::getFileFromUpload($request);
        //Check we have a file we're allowed to upload and store, if not, throw an error
        if (!$this->file::isTypeAllowed($fileEntity->mime, $this->file::defaultAllowedTypes())) {
            $this->output::addMessage('core.file.upload', 'error', 'File type of '.$fileEntity->mime.' not allowed');
            return System::asJson($response, ['success' => false], 403);
        }

        $path = $this->file::storeUploadedFile($fileEntity->getMetadata('uploadedFile'));
        $fileEntity->path = $path;
        $fileEntity->store();

        $this->output::addMessage('core.file.upload', 'success', 'File type of '.$fileEntity->mime.' uploaded.');
        $this->output::addResponse($request, ['fid' => $fileEntity->id]);
        return System::asJson($response);
    }


    public function download(Request $request,Response $response, $args) {
        $fileEntity = new fileEntity();
        $fileEntity->load($args['id']);

        if ($fileEntity->created_by != $this->currentUser->id) {
            $this->output::addMessage('core.file.download', 'error', 'You are forbidden from accessing this file');
            return System::asJson($response, [], 403);
        }

        if(!isset($fileEntity->id)){
            $this->output::addMessage('core.file.download', 'error', 'File not yet ready for download');
            return System::asJson($response, [], 500);
}

        $data = [
            'contentType' => $fileEntity->mime,
            'filename' => basename($fileEntity->path),
            'data' => file_get_contents($fileEntity->path)
        ];

        return System::asJson($response, $data);
    }
}