<?php

namespace Cadoles\WebsocketBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Form\FormError;
use Ramsey\Uuid\Uuid;

use Cadoles\WebsocketBundle\Form\ChatType;

class ChatController extends Controller
{
    public function clientAction($id, Request $request)
    {
        $user=$this->getUser();
        if(!$user) {
            die();
        }
        else {
            $framed=$request->query->get('framed');
            if($framed) {
                $border=$request->query->get('border');
                if($border) {
                    $colorbodyback=$request->query->get('colorbodyfont');
                    $colorbodyfont=$request->query->get('colorbodyback');    
                }
                else {
                    $colorbodyback=$request->query->get('colorbodyback');
                    $colorbodyfont=$request->query->get('colorbodyfont');    
                }

                $colorbody=$request->query->get('colorbody');
                $colormain=$request->query->get('colormain');
            }
            else {
                $border=false;
                $colorbodyback=$this->get('session')->get('color')["main"];
                $colorbodyfont=$this->get('session')->get('color')["fontcolorhover"];                 
                $colorbody=$this->get('session')->get('color')["colorbody"];
                $colormain=$this->get('session')->get('color')["main"];
            }

            $em = $this->getDoctrine()->getManager();

            // On récupère les 100 derniers message du groupe
            $group=$em->getRepository("CadolesCoreBundle:Group")->find($id);
            if(!$group) die();

            // Génération d'une clé temporaire d'accès au chat
            $usergroup=$em->getRepository("CadolesCoreBundle:UserGroup")->findOneBy(["group"=>$group,"user"=>$user]);
            $key=null;
            if($usergroup) {
                $key=$usergroup->getKeyvalue();
                if(is_null($key)) {
                    $key = Uuid::uuid4();
                    $usergroup->setKeyvalue($key);
                    $em->persist($usergroup);
                    $em->flush();
                }  
            }


            // Récupération des message parent du groupe
            $messages=$em->getRepository("CadolesWebsocketBundle:Message")->findBy(["group"=>$group,"parent"=>null],["submitdate"=>"DESC"]);
            foreach($messages as $message) { 
                $haveread = ($message->getReaders()->contains($user));
                $havesee = ($message->getSees()->contains($user));

                $message->setHaveread($haveread);
                $message->setHavesee($havesee);
                
                if(!$haveread) {
                    $message->addReader($this->getUser());
                    $em->persist($message);
                    $em->flush();                  
                }

                foreach($message->getChilds() as $child) {
                    $haveread = ($child->getReaders()->contains($user));
                    $havesee = ($child->getSees()->contains($user));
    
                    $child->setHaveread($haveread);
                    $child->setHavesee($havesee);
                    
                    if(!$haveread) {
                        $child->addReader($this->getUser());
                        $em->persist($child);
                        $em->flush();                  
                    }
                }
            }

            // Création du formulaire
            $form = $this->createForm(ChatType::class,null,[]);

            // Affichage du chat
            return $this->render('CadolesWebsocketBundle:Chat:client.html.twig',[
                'useheader'         => false,
                'usemenu'           => false,
                'usesidebar'        => false,
                'userkey'           => $key,
                'groupid'           => $id,
                'group'             => $group,
                'messages'          => $messages,
                'framed'            => $framed,
                'border'            => $border,
                'colorbodyback'     => $colorbodyback,
                'colorbodyfont'     => $colorbodyfont,
                'colorbody'         => $colorbody,
                'colormain'         => $colormain,
                'ingroup'           => ($usergroup),
                'canmanage'         => ($usergroup&&($usergroup->getRolegroup()>=90||$user->getRole()=="ROLE_ADMIN"||$user->getRole()=="ROLE_MODO")),
                'form'              => $form->createView()
            ]);
        }
    }

    public function seeAction(Request $request)
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }
        
        $em = $this->getDoctrine()->getManager();

        $output=array();
        $id=$request->request->get('id');
        $user=$this->getUser();
        if($user) {
            $message=$em->getRepository("CadolesWebsocketBundle:Message")->find($id);
            $message->addSee($user);
            // Sauvegarde
            $em->persist($message);
            $em->flush();            
        }

        $response = new Response(json_encode($output));    
        $response->headers->set('Content-Type', 'application/json');        
        return $response;        
    }

    public function listAction(Request $request) {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }   

        $em = $this->getDoctrine()->getManager();
        $id=$request->request->get('id');
        $output=array();

        // On récupère le groupe
        $group=$em->getRepository("CadolesCoreBundle:Group")->find($id);
        if(!$group) die();

        // On récupere le user        
        $user=$this->getUser();
        if(!$user) die();

        // On récupère le lien usergroup
        $usergroup=$em->getRepository("CadolesCoreBundle:UserGroup")->findOneBy(["group"=>$group,"user"=>$user]);
        if(!$usergroup) die();
        
        // On récupere les messages parent
        $messages=$em->getRepository("CadolesWebsocketBundle:Message")->findBy(["group"=>$group,"parent"=>null],["submitdate"=>"DESC"],10);

        foreach($messages as $message) {
            $tmp=[];
            $tmp["id"]=$message->getId();
            $tmp["message"]=$message->getTopic();
            $tmp["submitdate"]=$message->getSubmitdate();
            $tmp["userid"]=$message->getUser()->getId();
            $tmp["userlastname"]=$message->getUser()->getLastname()." ".$message->getUser()->getFirstname();
            $tmp["useravatar"]=$message->getUser()->getAvatar();
            $tmp["childs"]=[];

            foreach($message->getChilds() as $child) {
                $tmpchild=[];
                $tmpchild["id"]=$child->getId();
                $tmpchild["message"]=$child->getTopic();
                $tmpchild["submitdate"]=$child->getSubmitdate();
                $tmpchild["userid"]=$child->getUser()->getId();
                $tmpchild["userlastname"]=$child->getUser()->getLastname()." ".$child->getUser()->getFirstname();
                $tmpchild["useravatar"]=$child->getUser()->getAvatar();

                array_push($tmp["childs"],$tmpchild);
            }

            array_push($output,$tmp);
        }

        $response = new Response(json_encode($output));    
        $response->headers->set('Content-Type', 'application/json');        
        return $response;               
    }         
}
