<?php 

namespace NPS\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use NPS\Factory\UserQueryFactory;
use NPS\Repository\UserQueryRepository;
use NPS\Repository\UserRepository;
use NPS\Model\AbstractUserQuery;
use NPS\Repository\FileRepository;
use NPS\Factory\FileFactory;
use NPS\Model\File;
use NPS\Exception\UnsupportedFileException;
use NPS\Exception\MissingArgumentException;
use NPS\DependencyInjection\Mailer;

/**
 * Controller for user query related functions
 * @author Lukas Korinek
 */
class UserQueryController extends AbstractController
{

    /**
     * @Route("/user-query/report", methods={"POST"})
     */ 
    public function reportErrorAction(UserQueryFactory $factory, UserRepository $userRepo, FileFactory $fileFactory, FileRepository $fileRepo, Request $request, Mailer $mailer)
    {
        if(!$email = trim($request->get('email')))
        {
            if(!$this->getUser())
            {
                throw new MissingArgumentException('email');
            }

            $email = null;
        }

        if(!$text = trim($request->get('text')))
        {
            throw new MissingArgumentException('text');
        }

        $user = $this->getUser();
        $history = $request->get('history') ? json_decode($request->get('history')) : [];

        $attachment = $request->files->has('attachment') ? $fileFactory->createFromRequest($fileRepo->getNewId(), $request->files->get('attachment'), $user, ['error_reporting'], false) : null;
        if($attachment && $attachment->getType() != File::FILE_IMAGE)
        {
            throw new UnsupportedFileException($request->files->get('attachment')->getMimeType());
        }

        $factory->create(UserQueryFactory::USER_QUERY_ERROR_REPORTING, $text, $email, $user, $attachment, $history);
        $mailer->sendAll();
        $this->flush();

        return $this->response();
    }

    
    /**
     * @Route("/user-query/question", methods={"POST"})
     */ 
    public function questionAction(UserQueryFactory $factory, Request $request, Mailer $mailer)
    {
        if(!$email = trim($request->get('email')))
        {
            throw new MissingArgumentException('email');
        }

        if(!$text = trim($request->get('text')))
        {
            throw new MissingArgumentException('text');
        }

        $factory->create(UserQueryFactory::USER_QUERY_QUESTION, $text, $email);
        $mailer->sendAll();
        $this->flush();

        return $this->response();
    }

    /**
     * @Route("/user-query/list-reports")
     * @Security("is_granted('ROLE_ADMIN')")
     */ 
    public function listReportedErrorsAction(UserQueryRepository $repo, Request $request)
    {
        $limit = intval($request->get('limit', 50));
        $offset = intval($request->get('offset', 0));

        $reports = $repo->getAll(UserQueryFactory::USER_QUERY_ERROR_REPORTING, $limit, $offset);
        return $this->response([
            'reports' => array_map(function($report){

                return [
                    'email' => $report->getEmail(),
                    'text' => $report->getText(),
                    'attachment' => $report->getAttachment() ? $report->getAttachment()->getPath() : null,
                    'user_id' => $report->getUser() ? $report->getUser()->getId() : null,
                    'history' => $report->getUserHistory()
                ];
    
            }, $reports)
        ]);
    }

    /**
     * @Route("/user-query/list-questions")
     * @Security("is_granted('ROLE_ADMIN')")
     */ 
    public function listQuestionsAction(UserQueryRepository $repo, Request $request)
    {
        $limit = intval($request->get('limit', 50));
        $offset = intval($request->get('offset', 0));

        $reports = $repo->getAll(UserQueryFactory::USER_QUERY_QUESTION, $limit, $offset);
        return $this->response([
            'questions' => array_map(function($report){

                    return [
                        'email' => $report->getEmail(),
                        'text' => $report->getText()
                    ];

                } , $reports)
        ]);
    }
    
}


