<?php

namespace Cadoles\WebsocketBundle\Topic;

use Gos\Bundle\WebSocketBundle\Topic\TopicInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Wamp\Topic;
use Gos\Bundle\WebSocketBundle\Router\WampRequest;

use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Gos\Bundle\WebSocketBundle\Client\ClientManipulatorInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

use Cadoles\WebsocketBundle\Entity\Message;

class WebsocketTopic implements TopicInterface
{

    protected $em;
    protected $container;
    protected $clientManipulator;
    protected $users;

    public function __construct(ClientManipulatorInterface $clientManipulator, EntityManager $em, ContainerInterface $container) {
        $this->clientManipulator = $clientManipulator;
        $this->em = $em;
        $this->container = $container;
    }

    /**
     * This will receive any Subscription requests for this topic.
     *
     * @param ConnectionInterface $connection
     * @param Topic $topic
     * @param WampRequest $request
     * @return void
     */
    public function onSubscribe(ConnectionInterface $connection, Topic $topic, WampRequest $request)
    {      
        //this will broadcast the message to ALL subscribers of this topic.
        $topic->broadcast(['log' => $connection->resourceId." has joined ".$topic->getId()]);
    }

    /**
     * This will receive any UnSubscription requests for this topic.
     *
     * @param ConnectionInterface $connection
     * @param Topic $topic
     * @param WampRequest $request
     * @return void
     */
    public function onUnSubscribe(ConnectionInterface $connection, Topic $topic, WampRequest $request)
    {
        //this will broadcast the message to ALL subscribers of this topic.
        $topic->broadcast(['isdead' => 'isdead','userid'=>$connection->userId]);
    }


    /**
     * This will receive any Publish requests for this topic.
     *
     * @param ConnectionInterface $connection
     * @param Topic $topic
     * @param WampRequest $request
     * @param $event
     * @param array $exclude
     * @param array $eligible
     * @return mixed|void
     */
    public function onPublish(ConnectionInterface $connection, Topic $topic, WampRequest $request, $event, array $exclude, array $eligible)
    {
        $groupid=$request->getAttributes()->get('group');
        if(!is_array($event)) $event=json_decode($event, true);

        $group=$this->em->getRepository("CadolesCoreBundle:Group")->find($groupid);
        if(!$group) {
            $topic->broadcast(['log' => 'group NOT FIND']);
        }

        $usergroup=$this->em->getRepository("CadolesCoreBundle:UserGroup")->findOneBy(['keyvalue'=>$event["mykey"]]);
        if(!$usergroup) {
            $topic->broadcast(['log' => $event]);
            $topic->broadcast(['log' => 'user '.$event["mykey"].' NOT IN GROUP '.$groupid]);
        }
        else {
            $user=$usergroup->getUser();
        }

        if($group&&$usergroup&&$user) {
            if($event["type"]=="islive") {
                $topic->broadcast([
                    "islive" => "islive",
                    "userid" => $event["userid"],
                    "useravatar" => $event["useravatar"],
                    "userlastname" => $event["userlastname"],
                    "userfirstname" => $event["userfirstname"],                
                ]);
                $connection->userId=$event["userid"];
            }

            if($event["type"]=="meto") {
                $topic->broadcast([
                    "meto" => "meto",
                    "userid" => $event["userid"],
                    "useravatar" => $event["useravatar"],
                    "userlastname" => $event["userlastname"],
                    "userfirstname" => $event["userfirstname"],
                ]);
            }        
            
            if($event["type"]=="add") {
                if(array_key_exists("mail",$event)) {
                    $mail = $this->container->get('cadoles.core.service.mail');
                    if($mail) {
                        $pages=$group->getPages();
                        $pageid=$pages[0]->getId();
                        $cplt="<br><br><b>Attention pour répondre à ce message : n’utilisez pas votre mail mais rendez vous dans ce groupe sur Transnum et utilisez le fil de conversation (chat)</b><br>";
                        $url="https://".$this->container->getParameter('weburl')."/".$this->container->getParameter('alias').$this->container->get('router')->generate('cadoles_core_redirect', ['route'=>'cadoles_core_home','id'=>$pageid]);
                        $cplturl="<br><a href='".$url."'>".$url."</a>";
                        $mail_params=array(
                            "subject" => $event["subject"],
                            "body_html"=>$event["message"].$cplt.$cplturl,
                            "body_text"=>strip_tags($event["message"].$cplt.$url)
                        );    
    
                        // Transformer la liste des destinataires en tableau : [0] tjr vide on l'unset
                        $to=explode(";",$event["to"]); 
                        unset($to[0]);    

                        $mail->sendEmail("template", $mail_params, $to,  $this->container->getParameter('noreply'), $user->getLastname()." ".$user->getFirstname());                    
                        $event["message"].="<br><i>Notification envoyée par mail</i>";
                    }
                }

                $message=new Message();
                $message->setTopic($event["message"]);
                $message->setUser($user);
                $message->setGroup($group);
                $this->em->persist($message);
                $this->em->flush();

                $return["id"]=$message->getId();
                $return["lastname"]=$user->getLastname()." ".$user->getFirstname();
                $return["avatar"]=$user->getAvatar();
                $return["submitdate"]=$message->getSubmitdate();
                $return["message"]=$event["message"];
                $return["userid"]=$user->getId();

                //this will broadcast the message to ALL subscribers of this topic.
                $topic->broadcast(['msg' => $return]);
            }

            if($event["type"]=="reply") {
                $parent=$this->em->getRepository("CadolesWebsocketBundle:Message")->find($event["parent"]);
                if($parent) {
                    if(array_key_exists("mail",$event)) {
                        $mail = $this->container->get('cadoles.core.service.mail');
                        if($mail) {
                            $pages=$group->getPages();
                            $pageid=$pages[0]->getId();
                            $cplt="<br><br><b>Attention pour répondre à ce message : n’utilisez pas votre mail mais rendez vous dans ce groupe sur Transnum et utilisez le fil de conversation (chat)</b><br>";
                            $url="https://".$this->container->getParameter('weburl')."/".$this->container->getParameter('alias').$this->container->get('router')->generate('cadoles_core_redirect', ['route'=>'cadoles_core_home','id'=>$pageid]);
                            $cplturl="<br><a href='".$url."'>".$url."</a>";
                            $mail_params=array(
                                "subject" => $event["subject"],
                                "body_html"=>$event["message"].$cplt.$cplturl,
                                "body_text"=>strip_tags($event["message"].$cplt.$url)
                            );    
        
                            // Transformer la liste des destinataires en tableau : [0] tjr vide on l'unset
                            $to=explode(";",$event["to"]); 
                            unset($to[0]);    
    
                            $mail->sendEmail("template", $mail_params, $to,  $this->container->getParameter('noreply'), $user->getLastname()." ".$user->getFirstname());                    
                            $event["message"].="<br><i>Notification envoyée par mail</i>";
                        }
                    }

                    $message=new Message();
                    $message->setTopic($event["message"]);
                    $message->setUser($user);
                    $message->setGroup($group);
                    $message->setParent($parent);
                    $this->em->persist($message);
                    $this->em->flush();

                    // Si commentaire sur une message : il faut replacer le message en unsee pour tt le monde
                    foreach($parent->getSees() as $see) {
                        $parent->removeSee($see);
                    }
                    $this->em->persist($parent);
                    $this->em->flush();


                    $return["id"]=$message->getId();
                    $return["lastname"]=$user->getLastname()." ".$user->getFirstname();
                    $return["avatar"]=$user->getAvatar();
                    $return["submitdate"]=$message->getSubmitdate();
                    $return["message"]=$event["message"];
                    $return["userid"]=$user->getId();
                    $return["parent"]=$event["parent"];

                    //this will broadcast the message to ALL subscribers of this topic.
                    $topic->broadcast(['msgreply' => $return]);
                }
                else 
                    $topic->broadcast(['log' => "Message parent introuvable"]);
            }

            if($event["type"]=="del") {
                $message=$this->em->getRepository("CadolesWebsocketBundle:Message")->find($event["id"]);
                if($message&&($usergroup->getRolegroup()>=90||$message->getUser()==$user||$user->getRole()=="ROLE_ADMIN"||$user->getRole()=="ROLE_MODO" )) {
                    $id=$message->getId();
                    $this->em->remove($message);
                    $this->em->flush();
                    $topic->broadcast(['del' => $id]);
                }
                else $topic->broadcast(['log' => "Suppression interdite"]);
            }
        }
    }

    /**
    * Like RPC is will use to prefix the channel
    * @return string
    */
    public function getName()
    {
        return 'websocket.topic';
    }
}