<?php

namespace App\Presentation\Editor;

use App\Model\ArticleManager;
use App\Model\EditorManager;
use App\Presentation\BasePresenter;

class EditorPresenter extends BasePresenter
{
    private EditorManager $editorManager;
    private ArticleManager $articleManager;

    public function __construct(EditorManager $editorManager, ArticleManager $articleManager)
    {
        parent::__construct();
        $this->editorManager = $editorManager;
        $this->articleManager = $articleManager;
    }

    public function startup(): void
    {
        parent::startup();
        if (!$this->getUser()->isLoggedIn())
        {
            $this->error("403", 403);
        }
    }

    public function actionCreatearticle(): void
    {
        $user = $this->getUser();
        if (!$user->isLoggedIn() || !$user->isAllowed('article', 'create')) {
            $this->error("403", 403);
        }

        $data = $this->getPayloadJsonAndCheckRequest([
            'title', 'type', 'short_description', 'content', 'time_estimate', 'difficulty', 'topic_id'
        ]);
        $articleId =$this->editorManager->createArticle($this->getUser()->getId(), $data);

        if ($this->getUser()->isAllowed('article', 'approve')) {
            $this->editorManager->setArticleStatus($articleId, 'APPROVED');
        }
        $this->sendJson(['articleId' => $articleId]);
    }

    public function actionUpdatearticle($articleId): void
    {
        $user = $this->getUser();

        if (!$user->isLoggedIn()) {
            $this->error('Forbidden', 403);
        }

        $article = $this->articleManager->getArticle($articleId);
        if (!$article) {
            $this->error('Not Found', 404);
        }

        if (
            // Muze editovat cokoliv
            !(($this->getUser()->isAllowed('article', 'edit-all')) ||

            // Muze editovat pouze sve a tohle je jeho
            ($this->getUser()->isAllowed('article', 'edit-self') && $article->users_id == $this->getUser()->getId()))
        ) {
            $this->error("Forbidden", 403);
        }

        $payload = $this->getPayloadJsonAndCheckRequest([
            'title', 'type', 'short_description', 'content', 'time_estimate', 'difficulty', 'topic_id'
        ]);

        $this->editorManager->updateArticle($articleId, $payload);
        $this->sendJson(['success' => true]);
    }

    public function renderSetarticlestatus($articleId, $newStatus)
    {
        $user = $this->getUser();

        if (!$user->isLoggedIn()) {
            $this->error("403", 403);
        }

        $article = $this->articleManager->getArticle($articleId);

        if (!$article) {
            $this->error('Not Found', 404);
        }

        if (
            // Muze schvalovat
            !(($this->getUser()->isAllowed('article', 'approve')) ||

            // Muze editovat pouze sve a chce predlozit ke schvaleni
            ($this->getUser()->isAllowed('article', 'edit-self') &&
             $article->users_id == $this->getUser()->getId()) &&
             $newStatus == "TO_CHECK"
            )
        ) {
            $this->error("403", 403);
        }

        $this->editorManager->setArticleStatus($articleId, $newStatus);
        $this->sendJson(['success' => true]);
    }

    public function renderSetarticlesstatus($newStatus)
    {
        $user = $this->getUser();

        if (!$user->isLoggedIn()) {
            $this->error("403", 403);
        }

        if (!(($this->getUser()->isAllowed('article', 'approve')))) {
            $this->error("403", 403);
        }

        $articles = $this->getPayloadJsonAndCheckRequest(['ids'])['ids'];

        if (sizeof($articles) < 1) {
            $this->sendJson(['success' => false]);
        }

        $this->editorManager->setArticleStatus($articles, $newStatus);
        $this->sendJson(['success' => true]);
    }

    public function actionUploadarticlefiles($articleId): void
    {
        if (!$this->getUser()->isLoggedIn()) {
            $this->error("User is not logged in", 403);
        }

        if (
            // Muze editovat cokoliv
        !(($this->getUser()->isAllowed('article', 'edit-all')) ||

            // Muze editovat pouze sve a tohle je jeho
            ($this->getUser()->isAllowed('article', 'edit-self') && $this->articleManager->getArticle($articleId)->users_id == $this->getUser()->getId()))
        ) {
            $this->error("Forbidden", 403);
        }

        $files = $this->getUploadedFilesAndCheckRequest();
        $isOk = true;

        foreach ($files as $file) {
            if (!$this->editorManager->uploadFileToArticle($articleId, $file)) {
                $isOk = false;
            }
        }

        if (!$isOk) {
            $this->error("There was an error while uploading files.", 400);
        }

        $this->sendJson(["success" => $isOk, "files_count" => sizeof($files)]);
    }

    function renderGetarticle(int $articleId): void
    {
        // sanity check
        if ($articleId == null || !is_numeric($articleId))
            $this->error("Invalid article ID", 403);


        $article = $this->articleManager->getArticle($articleId);

        if ($article == null)
            $this->error("Article was not found.", 404);

        if (
            // Muze editovat cokoliv
        !(($this->getUser()->isAllowed('article', 'edit-all')) ||

            // Muze editovat pouze sve a tohle je jeho
            ($this->getUser()->isAllowed('article', 'edit-self') && $article->users_id == $this->getUser()->getId()))
        ) {
            $this->error("Forbidden", 403);
        }

        $output = [
            'id' => $article['id'],
            'content' => json_decode($article['content']),
            'title' => $article['title'],
            'type' => $article['type'],
            'short_description' => $article['short_description'],
            'time_estimate' => $article['time_estimate'],
            'difficulty' => $article['difficulty'],
            'created_at' => $article['created_at'],
        ];

        $output['files'] = [];
        $this->prepareObjectsOutput($output['files'], $this->articleManager->getFiles($articleId), ['id', 'name']);
        $this->sendJson($output);
    }
}