<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Ad;
use AppBundle\Entity\Media;
use AppBundle\Entity\User;
use AppBundle\Form\MediaType;
use AppBundle\Form\ProfileLogoType;
use AppBundle\Form\ProfilePictureType;
use Edeclic\PrestashopBridgeBundle\Event\PrestashopBridgeEvents;
use Edeclic\PrestashopBridgeBundle\Event\UserEvent;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;

class MediaController extends Controller
{
    /**
     * @Route("/entreprise/me/videotheque", name="company_media")
     */
    public function companyMediaAction(Request $request)
    {
        $event = new UserEvent($this->getUser());
        $this->get('event_dispatcher')->dispatch(PrestashopBridgeEvents::USER_PROD_UPDATE, $event);
        $em = $this->getDoctrine()->getManager();
        $medias = $em->getRepository('AppBundle:Media')->findBy(array('creator' => $this->getUser()));
        $form = $this->createForm(MediaType::class);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $title = $form['title']->getData();
            $idMedia = $form['media']->getData();
            $media = $em->getRepository('AppBundle:Media')->findOneBy(array('id' => $idMedia, 'creator' => $this->getUser()));
            $media->setTitle($title);
            $em->persist($media);
            $em->flush();

            return $this->redirectToRoute('company_media');
        }

        return $this->render('media/media_list.html.twig', array(
            'form' => $form->createView(),
            'medias' => $medias,
        ));
    }

    /**
     * @Route("/territoire/me/videotheque", name="territory_media")
     */
    public function territoryMediaAction(Request $request)
    {
        $event = new UserEvent($this->getUser());
        $this->get('event_dispatcher')->dispatch(PrestashopBridgeEvents::USER_PROD_UPDATE, $event);
        $em = $this->getDoctrine()->getManager();
        $medias = $em->getRepository('AppBundle:Media')->findBy(array('creator' => $this->getUser()));
        $form = $this->createForm(MediaType::class);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $title = $form['title']->getData();
            $idMedia = $form['media']->getData();
            $media = $em->getRepository('AppBundle:Media')->findOneBy(array('id' => $idMedia, 'creator' => $this->getUser()));
            $media->setTitle($title);
            $em->persist($media);
            $em->flush();

            return $this->redirectToRoute('territory_media');
        }

        return $this->render('media/media_list.html.twig', array(
            'form' => $form->createView(),
            'medias' => $medias,
        ));
    }

    /**
     * @Route("/talent/me/videotheque", name="talent_media")
     */
    public function talentMediaAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $medias = $em->getRepository('AppBundle:Media')->findBy(array('creator' => $this->getUser()));
        $form = $this->createForm(MediaType::class);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $title = $form['title']->getData();
            $idMedia = $form['media']->getData();
            $media = $em->getRepository('AppBundle:Media')->findOneBy(array('id' => $idMedia, 'creator' => $this->getUser()));
            $media->setTitle($title);
            $em->persist($media);
            $em->flush();
            return $this->redirectToRoute('talent_media');
        }

        return $this->render('media/media_list_talent.html.twig', [
            'form' => $form->createView(),
            'medias' => $medias,
        ]);
    }

    /**
     * @Route("/media/create/{id}", name="create_media")
     * @Security("ad.getStatus() == 'DRAFT' or ad.getStatus() == 'DECLINED'")
     */
    public function createMediaAction(Request $request, Ad $ad)
    {
        if ($this->container->has('profiler')) {
            $this->container->get('profiler')->disable();
        }
        if ($ad) {
            $video = $ad->getVideo();
        }
        // Get Avalaible videos
        $em = $this->getDoctrine()->getManager();
        $videos = $em->getRepository('AppBundle:Media')->findBy(array('creator' => $this->getUser()));
        $form = $this->createFormBuilder($video)
            ->add('title', TextType::class, array(
                'label' => 'Titre de la vidéo',
                'required' => true,
            ))
            ->getForm();
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $media = $form->getData();
            $em->persist($media);
            $em->flush();
            return $this->redirectToRoute('company_ad_step3', array('id' => $ad->getId()));
        }

        return $this->render('company/createMedia.html.twig', array(
            'form' => $form->createView(),
            'ad' => $ad,
            'video' => $video,
            'videos' => $videos,
        ));
    }

    /***********************
     * Ajax & Webservices
     ***********************/

     /**
     * @Route("/media/changeThumbnail", name="video_changeThumbnail")
     */
    public function changeThumbnailAction(Request $request)
    {
        $data = json_decode($request->getContent());
        $mediaManager = $this->get('media_manager');
        $message = $mediaManager->changeThumbnail($data->duration, $data->id);
     
        return new JsonResponse($message);
    }

    /**
     * @Route("/media/upload/{id}", name="upload_media")
     */
    public function uploadAction(Request $request, Ad $ad)
    {
        $message = array('success' => 200,
            'filename' => null,
            'originalFilename' => null,
        );
        foreach ($request->files as $uploadedFile) {
            $mediaManager = $this->get('media_manager');
            $message = $mediaManager->upload($ad, $uploadedFile, $ad->getCreator());
        }

        return new JsonResponse($message);
    }

    /**
     * @Route("/media/uploadDefault/{id}", name="upload_media_default")
     */
    public function uploadDefaultAction(Request $request, User $user)
    {
        $message = array('success' => 200,
            'filename' => null,
            'originalFilename' => null,
        );
        foreach ($request->files as $uploadedFile) {
            $mediaManager = $this->get('media_manager');
            $message = $mediaManager->upload(null, $uploadedFile, $user);
        }

        return new JsonResponse($message);
    }

    /**
     * @Route("/media/uploadPresentation", name="upload_media_presentation")
     */
    public function uploadPresentationAction(Request $request)
    {
        $message = array('success' => 200,
            'filename' => null,
            'originalFilename' => null,
        );
        foreach ($request->files as $uploadedFile) {
            $mediaManager = $this->get('media_manager');
            $message = $mediaManager->upload($this->getUser(), $uploadedFile, $this->getUser());
        }

        return new JsonResponse($message);
    }

    /**
     * @Route("/media/delete/video/{id}", name="delete_unattached_media")
     */
    public function removeUnattachedMediaAction(Request $request, Media $media)
    {
        $mediaManager = $this->get('media_manager');
        $mediaManager->delete($media);
        $message = array('success' => 200);

        return new JsonResponse($message);
    }

    /**
     * @Route("/media/delete/{id}", name="delete_media")
     */
    public function removeFileAction(Request $request, Ad $ad)
    {
        $mediaManager = $this->get('media_manager');
        $message = $mediaManager->remove($ad);

        return new JsonResponse($message);
    }

    /**
     * @Route("/media/edit/title/{id}", name="media_edit_title")
     */
    public function mediaEditTitleAction(Request $request, Media $media)
    {

        $em = $this->getDoctrine()->getManager();
        $media->setTitle($request->get('title'));
        $em->persist($media);
        $em->flush();

        return new JsonResponse(array('success' => "true"));
    }

    /**
     * @Route("/media/link/{id}", name="link_media")
     */
    public function mediaLinkAction(Request $request, Ad $ad)
    {
        $em = $this->getDoctrine()->getManager();
        $video = $em->getRepository('AppBundle:Media')->find($request->request->get('idVideo'));
        $ad->setVideo($video);
        $em->persist($ad);
        $em->flush();

        return new JsonResponse(array('success' => "true"));
    }

    /**
     * @Route("/media/default", name="media_default")
     */
    public function mediaDefaultAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $idVideo = $request->get('idVideo');
        $idUser = $request->get('idUser');
        if ($idVideo == null) {
            $user = $em->getRepository('AppBundle:User')->findOneBy(array('id' => $idUser));
            $company = $user->getCompany();
            $company->setPresentationVideo(null);
        } else {
            $user = $em->getRepository('AppBundle:User')->findOneBy(array('id' => $idUser));
            $video = $em->getRepository('AppBundle:Media')->findOneBy(array('id' => $idVideo));
            $company = $user->getCompany();
            if ($user->hasRole('ROLE_TALENT') || $user->hasRole('ROLE_TERRITORY') || ($user->hasRole('ROLE_COMPANY') && $company->hasCompanyVideo())) {
                $company->setPresentationVideo($video);
            }
        }
        try {
            $em->persist($company);
            $em->flush($company);
            $response = array("code" => 200, "success" => true);
            $response = new Response(json_encode($response));
            $response->send();
        } catch (\Doctrine\ORM\EntityNotFoundException $ex) {
            $response = array("code" => 500, "success" => false);
            $response = new Response(json_encode($response));
            $response->send();
        }
    }

    //upload profile picture

    /**
     * @Route("/media/profile/picture", name="profile_picture")
     */
    public function profilePictureAction(Request $request)
    {
        $userManager = $this->get('fos_user.user_manager');
        $user = $this->getUser();
        $form = $this->createForm(ProfilePictureType::class, $user);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $user->upload();
            $userManager->updateUser($user);
            $this->addFlash(
                'notice',
                $this->get('translator')->trans('Photo de profil modifié')
            );
            return $this->redirect($this->generateUrl('talent_dashboard'));
        }
        return $this->render('profile/form_picture.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/media/profile/logo", name="profile_logo")
     */
    public function profileLogoAction(Request $request)
    {
        $user = $this->getUser();
        $company = $user->getCompany();
        $form = $this->createForm(ProfileLogoType::class, $company);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $companyManager = $this->get('app.company_manager');
            $companyManager->updateLogo($company);
            $this->addFlash(
                'notice',
                $this->get('translator')->trans('Le logo de votre entreprise a bien été modifié')
            );
            return $this->redirect($this->generateUrl('company_dashboard'));
        }
        return $this->render('profile/form_logo.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/media/import/cv/{type}", name="media_import_cv")
     * @security("type == 'webcam' or type == 'import'")
     */
    public function importCVAction(Request $request, $type = 'webcam')
    {
        $securityContext = $this->container->get('security.authorization_checker');
        if (!$securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
            return $this->redirectToRoute('talent_cv_import');
        }
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();
        $mustLogin = false;
        if (!$user->hasRole('ROLE_TALENT')) {
            $mustLogin = true;
        }

        /*Definition des urls de destination pour oauth login et register*/
        $destination_login = $this->generateUrl('talent_media');
        $this->get('twig')->addGlobal('destination_login', $destination_login);
        $session = new Session();
        $session->set('registration_destination', $destination_login);

        $res = $this->render('media/media_create_' . $type . '.twig', array(
            'video' => null,
            'mustLogin' => $mustLogin,
        ));
        $res->headers->setCookie(new Cookie('redirect_register', $destination_login));
        return $res;
    }

}
