{% extends '@CadolesCore/base.html.twig' %}

{% block localstyle %}
    {% if framed %}
        {% if border %}
            #topchat {
                margin: 5px -15px 5px -25px;
            }
            .mychat{
                margin: 0px 0px 0px -10px;
            }            
        {% else %}
            #topchat {
                margin: 5px -30px;
            }
            .mychat{
                margin: 0px -15px;
            }
        {% endif %}
    {% else %}
        #topchat { padding-top:20px; padding-bottom:30px; }
    {% endif %}

    .message {
        padding:10px;
        margin-top: 5px;
        background-color: #{{ colorbodyback }};
        color: #{{ colorbodyfont }};
    }
    .message-toread { 
        font-weight:bold;
    }
    .message-see { 
        display:none;
    }

    .msgavatar {
        float:left;
        height:40px;
        text-align: center;
    }
    .msgdiv {
        padding-left:60px;
    }
    .msgtitle {
        line-height: 12px;
        margin-bottom: 10px;
    }
    .msgreplys {
        margin-bottom:10px;
    }
    .messagereply {
        padding:0px;
        border-top: 1px solid #{{ colorbodyfont }};
        font-size:12px;
    }

    .btnreplymessage, .btnreplymessagemail {
        padding: 5px;
        background-color: #{{ colorbodyfont }};
        color : #{{ colorbodyback }};
        border-radius:5px;
        cursor:pointer;
        margin-right:5px;
    }
    .btnreplymessage:hover, .btnreplymessagemail:hover {
        color : #{{ colorbodyback }};
    }
    .replymessage { display:none}
    .replymessage textarea {
        width:100%;
        margin:20px 0px 5px 0px;
        height:150px;
        color:#000000;
    }
    .sendreply { width:100%}

    .bootstrap-switch{
        margin-top:5px;
    }
    .labelswitch {
        line-height: 40px;
        float: right;
        margin-right: 10px;        
    }
    #listtoavatar img {
        margin:0px 5px 5px 0px; 
        cursor:pointer;
    }
    .cke_bottom{ display:none }
{% endblock %}

{% block pagewrapper %}
    {% set colorlabel= colormain %}
    {% if border  %}
        {% set colorlabel = colorbody %}
    {% endif %}
    {% if colorbody==colorbodyfont %}
        {% set colorlabel = colorbodyback %}
    {% endif %}
    
    {% if app.user and ingroup %}
    {{ form_start(form) }}
    <div id="topchat" class='row'>
        {{ form_widget(form.message) }}
        <input id="sendbymail" type="checkbox" style="float:right" class='switch' ></input>            
        <label class="custom-control-label" for="sendbymail" style="color:#{{ colorlabel }}">Envoyer par Mail ?</label>
        <a id="sendbtn" class="btn btn-success" style="margin-top:5px; width:100%; margin-bottom:15px">Envoyer</a>
        <div id="useronline" style="margin-bottom:10px"></div>
        <input id="unsee" type="checkbox" style="float:right" class='switch' onChange="switchsee()"></input>
        <label class="custom-control-label" for="unsee" style="color:#{{ colorlabel }}">Afficher les messages masqués ?</label>
    </div>
        
    

    <div class="mychat">
        {% for message in messages %}
            {% set classread="" %}
            {% if not message.haveread %}
                {% set classread="message-toread" %}
            {% endif %}

            {% set classsee="" %}
            {% if message.havesee %}
                {% set classsee="message-see" %}
            {% endif %}

            <div id='message-{{message.id}}'  class='message row {{classread}} {{classsee}}'>
                <div class='msgavatar'>
                    <img style='cursor:pointer' onclick='seeUser({{message.user.id}})' id='user_avatar_img' src='/{{ alias }}/uploads/avatar/{{message.user.avatar}}' class='avatar'><br>
                    {% if canmanage or message.user == app.user %}
                        <i class='delmessage fa fa-trash fa-fw' data-id='{{message.id}}' title='Supprimer' style='cursor: pointer;'></i>
                    {% endif %}
                    {% if not message.havesee %}
                        <i id="hidemessage-{{message.id}}" class='hidemessage fa fa-eye-slash fa-fw' title='Ne plus afficher' data-id='{{message.id}}' style='cursor: pointer;'></i>
                    {% endif %}
                </div>
                <div class='msgdiv'>
                    <div class='msgtitle'>
                        {{message.user.lastname}} {{message.user.firstname}}<br>
                        <small>{{message.submitdate|date('d/m/Y H:i')}}</small>
                    </div>
                    <div class='msgtopic'>{{message.topic | raw}}</div>

                    <div id="msgreplys-{{message.id}}" class='msgreplys'>
                        {% for child in message.childs | reverse %}
                            {% set classread="" %}
                            {% if not child.haveread %}
                                {% set classread="message-toread" %}
                            {% endif %}

                            {% set classsee="" %}
                            {% if child.havesee %}
                                {% set classsee="message-see" %}
                            {% endif %}

                            <div id='message-{{child.id}}' class='message messagereply {{classread}} {{classsee}}'>
                                {{child.topic | raw | nl2br   }}

                                <div style='cursor:pointer' onclick='seeUser({{child.user.id}})'><small>{{ child.user.lastname }} {{ child.user.firstname }}</small></div>
                                <small>{{child.submitdate|date('d/m/Y H:i')}}</small>
                                {% if canmanage or child.user == app.user %}
                                    <i class='delmessage fa fa-trash fa-fw' data-id='{{child.id}}' title='Supprimer' style='cursor: pointer;'></i>
                                {% endif %}
                                {% if not child.havesee %}
                                    <i id="hidemessage-{{child.id}}" class='hidemessage fa fa-eye-slash fa-fw' title='Ne plus afficher' data-id='{{child.id}}' style='cursor: pointer;'></i>
                                {% endif %}
                            </div>
                        {% endfor %}
                    </div>

                    <a class="btnreplymessage" data-id='{{message.id}}'>Répondre</a>
                    <a class="btnreplymessagemail" data-id='{{message.id}}'>Répondre par Mail</a>
                    <div id="replymessage-{{message.id}}" class="replymessage">
                        <textarea></textarea>
                        <a id="sendreply" class="btn btn-success sendreply" data-id='{{message.id}}'>Envoyer</a>
                    </div>
                </div>
            </div>
        {% endfor %}
    </div>

    <div id="mymodal-sendmail" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">Notifier par Mail</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group ">
                        <label class="control-label required" for="mailsuject">Sujet du Mail<span class="mandatory">*</span></label>
                        <input type="text" id="mailsuject" name="mailsuject" required="required" class="form-control">
                    </div>
                    <div>
                        <label class="control-label required">Destinataires<span class="mandatory">*</span></label>

                        <select id="destinataires" style="width:100%" name="states[]" multiple="multiple">
                            {% for user in group.users |sort((a, b) => a.user.lastname <=> b.user.lastname) %} %}
                                {%if(user.user!=app.user)%}
                                    <option value="{{user.user.email}}" data-image="\{{alias}}\uploads\avatar\{{user.user.avatar}}">{{user.user.lastname}} {{user.user.firstname}}</option>
                                {%endif%}
                            {% endfor %}
                        </select>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" value="" id="checkalldestinataires">
                            <label class="form-check-label" for="checkalldestinataires">
                               Tout le monde
                            </label>
                        </div>                        
                    </div>
                    <div class="form-group" style="margin-top:10px">
                        <label class="control-label required">Corps du Mail<span class="mandatory">*</span></label>
                        {{ form_widget(form.messagemail) }}
                    </div>
                    <a id="sendbtnmail" class="btn btn-success" style="margin-top:5px; width:100%; margin-bottom:15px">Envoyer</a>
                    <a id="sendbtnmailreply" class="btn btn-success" data-id="" style="margin-top:5px; width:100%; margin-bottom:15px">Envoyer</a>
                </div>
            </div>
        </div>
    </div>

    {{ form_end(form) }}
    {% endif %}
{% endblock %}

{% block localexternalscript %}
    <script src="/{{alias}}/bundles/goswebsocket/js/vendor/autobahn.min.js"></script>
    <script type="text/javascript" src="/{{alias}}/ckeditor/adapters/jquery.js"></script>
{% endblock %}

{% block localjavascript %}
    {% if websocket_activate and app.user %}
    var WS = (function()
    {
        var GosSocket = function(uri, sessionConfig){
            this._uri = uri;
            this._session = false;
            this._listeners = {};
            this.connect(sessionConfig);
        };

        GosSocket.prototype.connect = function (sessionConfig) {
            var that = this;

            ab.connect(this._uri,

                //Function on connect
                function(session){
                    that.fire({type: "socket/connect", data: session });
                },

                //Function on disconnect / error
                function(code, reason){
                    that._session = false;

                    that.fire({type: "socket/disconnect", data: {code: code, reason: reason}});
                },

                sessionConfig
            );
        };

        GosSocket.prototype.on = function(type, listener){
            if (typeof this._listeners[type] == "undefined"){
                this._listeners[type] = [];
            }

            this._listeners[type].push(listener);
        };

        GosSocket.prototype.fire = function(event){
            if (typeof event == "string"){
                event = { type: event };
            }
            if (!event.target){
                event.target = this;
            }

            if (!event.type){  //falsy
                throw new Error("Event object missing 'type' property.");
            }

            if (this._listeners[event.type] instanceof Array){
                var listeners = this._listeners[event.type];
                for (var i=0, len=listeners.length; i < len; i++){
                    listeners[i].call(this, event.data);
                }
            }
        };

        GosSocket.prototype.off = function(type, listener){
            if (this._listeners[type] instanceof Array){
                var listeners = this._listeners[type];
                for (var i=0, len=listeners.length; i < len; i++){
                    if (listeners[i] === listener){
                        listeners.splice(i, 1);
                        break;
                    }
                }
            }
        };

        return {
            connect: function(uri, sessionConfig)
            {
                return new GosSocket(uri, sessionConfig);
            }
        }

    })();
    {% endif %}

	$(document).ready(function(){
        if (CKEDITOR.instances["chat_message"]) CKEDITOR.instances["chat_message"].destroy();
        if (CKEDITOR.instances["chat_messagemail"]) CKEDITOR.instances["chat_messagemail"].destroy();

        setTimeout(function(){
            CKEDITOR.replace( 'chat_message', {
                toolbar: [
                    { name: 'custo01',   items: [ 'Bold','Italic','Underline','RemoveFormat' ] },
                    { name: 'custo02',   items: [ 'NumberedList','BulletedList' ] },
                    { name: 'custo03',   items: [ 'Smiley','Link','Unlink' ]}
                ],
                height: 100
            });

            CKEDITOR.replace( 'chat_messagemail', {
                toolbar: [
                    { name: 'custo01',   items: [ 'Bold','Italic','Underline','RemoveFormat' ] },
                    { name: 'custo02',   items: [ 'NumberedList','BulletedList' ] },
                    { name: 'custo03',   items: [ 'Smiley','Link','Unlink' ]}
                ],
                height: 150
            });
        },1000);
        
        $(".switch").bootstrapSwitch();
        $("#mymodal-sendmail").removeAttr("tabindex");

        websocket();

        /*
        setInterval(function(){ 
            islive();
        }, 15000);
        */
	});

    {% if websocket_activate and app.user %}
        
        var session;
        var dateoptions = {weekday: "long", year: "numeric", month: "long", day: "numeric", hour: "2-digit", minute:  "2-digit" };
        var timer;
        var delayRetry=500;
        var isdeco=false;
        var tosend=false;
        var tosendmail=false;
        var todelete=false;
        var idtodelete;
        var isalive;

        function websocket()
        {       
            var _WS_URI = "wss://{{ gos_web_socket_server_host }}";
            console.log(_WS_URI);
            webSocket = WS.connect(_WS_URI,{retryDelay: delayRetry});

            webSocket.on("socket/connect", function (sess) {  
                console.log("=== CONNECT ===");

                // Sauvegardce de la session
                session=sess;
                
                //the callback function in "subscribe" is called everytime an event is published in that channel.
                sess.subscribe("websocket/channel/{{groupid}}", function (uri, payload) {
                    
                    if(!isalive||isdeco) islive();

                    // Récupération lastmessage
                    if(isdeco) recuplastmsg();

                    // Si action en cours
                    if(tosend) sendbtn();
                    if(tosendmail) sendbtnmail();
                    if(todelete) delmessage(idtodelete);

                    // Il est co
                    isdeco=false;

                    if(payload.msg) {
                        html ="<div id='message-"+payload.msg.id+"' class='message row message-toread'>";
                        html+="<div class='msgavatar'>";
                        html+="<img style='pointer:cursor' onclick='seeUser("+payload.msg.userid+")' id='user_avatar_img' src='/{{ alias }}/uploads/avatar/"+payload.msg.avatar+"' class='avatar'><br>";
                        if(payload.msg.userid=={{app.user.id}} || '{{ canmanage }}'=='1') {
                            html+="<i class='delmessage fa fa-trash fa-fw' data-id='"+payload.msg.id+"' title='Supprimer' style='cursor: pointer;'></i>";
                        }
                        html+="<i id='hidemessage-"+payload.msg.id+"' class='hidemessage fa fa-eye-slash fa-fw' data-id='"+payload.msg.id+"' title='Ne plus afficher' style='cursor: pointer;'></i>";

                        html+="</div>";
                        html+="<div class='msgdiv'>"
                        html+="<div class='msgtitle'>"+payload.msg.lastname+"<br><small>"+new Date(payload.msg.submitdate.date).toLocaleDateString("fr-FR", dateoptions)+"</small></div>";
                        html+="<div class='msgtopic'>"+payload.msg.message+"</div>";
                        html+="<div id='msgreplys-"+payload.msg.id+"' class='msgreplys'></div>";
                        html+="<a class='btnreplymessage' data-id='"+payload.msg.id+"'>Répondre</a>";
                        html+="<a class='btnreplymessagemail' data-id='"+payload.msg.id+"'>Répondre par Mail</a>";
                        html+="<div id='replymessage-"+payload.msg.id+"' class='replymessage'>";
                        html+="<textarea></textarea>";
                        html+="<a id='sendreply' class='btn btn-success sendreply' data-id='"+payload.msg.id+"'>Envoyer</a>";
                        html+="</div>";                        
                        html+="</div>";
                        html+="</div>";
                        $(".mychat").prepend(html);

                        //console.log("Received message by "+payload.msg.userid+" = ",payload.msg);
                    }

                    if(payload.msgreply) {
                        // Si on reçoit une réponse forcement le parent est de nouveau visible
                        $("#message-"+payload.msgreply.parent).removeClass ("message-see");

                        // On ajout la réponse
                        html ="<div id='message-"+payload.msgreply.id+"' class='message messagereply message-toread'>";
                        html+=nl2br(payload.msgreply.message);
                        html+="<div style='cursor:pointer' onclick='seeUser("+payload.msgreply.userid+")'><small>"+payload.msgreply.lastname+"</small></div>";
                        html+="<small>"+new Date(payload.msgreply.submitdate.date).toLocaleDateString("fr-FR", dateoptions)+"</small>";
                        if(payload.msgreply.userid=={{app.user.id}} || '{{ canmanage }}'=='1') {
                            html+="<i class='delmessage fa fa-trash fa-fw' data-id='"+payload.msgreply.id+"' title='Supprimer' style='cursor: pointer;'></i>";
                        }
                        html+="<i id='hidemessage-"+payload.msgreply.id+"' class='hidemessage fa fa-eye-slash fa-fw' data-id='"+payload.msgreply.id+"' title='Ne plus afficher' style='cursor: pointer;'></i>";
                        html+="</div>";            

                        $("#msgreplys-"+payload.msgreply.parent).prepend(html);            
                    }

                    if(payload.log) {
                        console.log("Received message", payload.log);
                    }

                    if(payload.del) {
                        $("#message-"+payload.del).remove();
                    }

                    if(payload.alert) {
                        alert(payload.alert);
                    }

                    if(payload.islive) {
                        if(payload.userid!={{app.user.id}}) {
                            console.log("Received message islive", payload.userid);
                            addOnline(payload.userid, payload.useravatar, payload.userlastname, payload.userfirstname);
                            {% if app.user.visible %}
                            event={mykey: "{{userkey}}", type: "meto", userid: {{app.user.id}}, useravatar: "{{app.user.avatar}}", userlastname: "{{ app.user.lastname}}", userfirstname: "{{ app.user.firstname }}" };
                            session.publish("websocket/channel/{{groupid}}", event); 
                            {% endif %}
                            
                        }
                    }

                    if(payload.meto) {
                        console.log("Received message meto", payload.userid, payload.useravatar, payload.userlastname, payload.userfirstname);
                        addOnline(payload.userid, payload.useravatar, payload.userlastname, payload.userfirstname);
                    }      

                    if(payload.isdead) {
                        console.log("Received message isdead", payload.userid);
                        $("#online"+payload.userid).remove();
                    } 
                });
            });
            
            webSocket.on("socket/disconnect", function(error){
                laberror="Disconnected for " + error.reason + " with code " + error.code;
                console.log("=== DISCONNECT ===");
                console.log(laberror);
                isdeco=true;
            }); 
        }

        function nl2br (str, is_xhtml) {
            if (typeof str === 'undefined' || str === null) {
                return '';
            }
            var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
            return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
        }        

        function switchsee() {
            $(".message-see").hide();
            if($("#unsee").bootstrapSwitch('state')) {
                $(".message-see").show();
            }
        }

        $( "#sendbtn" ).click(function() {
            sendbtn();
        });

        function formatState (opt) {
            if (!opt.id) {
                return opt.text.toUpperCase();
            } 

            var optimage = $(opt.element).attr('data-image'); 
            console.log(optimage)
            if(!optimage){
            return opt.text.toUpperCase();
            } else {                    
                var $opt = $(
                '<span><img src="' + optimage + '" width="30px" height="30px" style="border-radius:100%"/> ' + opt.text + '</span>'
                );
                return $opt;
            }
        };

        $("#checkalldestinataires").click(function(){
            if($("#checkalldestinataires").is(':checked') ){
                $("#destinataires > option").prop("selected","selected");
                $("#destinataires").trigger("change");
            }else{
                $("#destinataires > option").removeAttr("selected");
                $("#destinataires").trigger("change");
            }
        });

        function sendbtn() {
            var data = CKEDITOR.instances["chat_message"].getData();
            if($("#sendbymail").bootstrapSwitch('state')) {
                CKEDITOR.instances["chat_messagemail"].setData(data);
                $("#mailsuject").val("{{app.session.get('appname')}} = Notification {{ group.label }}");
                
                $("#sendbtnmail").show();
                $("#sendbtnmailreply").hide();
                $('#mymodal-sendmail').modal('show');
                $("#checkalldestinataires").prop( "checked", false );
                $("#destinataires > option").removeAttr("selected");
                $("#destinataires").trigger("change");                
                $('#destinataires').select2({
                    templateResult: formatState,
                    templateSelection: formatState,
                    sorter: data => data.sort((a, b) => a.text.localeCompare(b.text)),
                });
            }
            else {
                if(data) {
                    try {
                        // Flager que l'envoit c'est fait
                        tosend=false;
                        $("#sendbtn").html("Envoyer");
                        $("#sendbtn").removeClass("btn-danger");
                        $("#sendbtn").css('cursor','auto');

                        // Push envent sur le websocket
                        event={mykey: "{{userkey}}", type: "add", message: data};
                        session.publish("websocket/channel/{{groupid}}", event);  
                        CKEDITOR.instances["chat_message"].setData('');
                    }
                    catch(error) {
                        // L'envoi ne s'est pas fait
                        console.log("Retry to send");

                        // On flag le fait de retenter l'envoit à la reconnexion
                        tosend=true;

                        // On signal que l'envoi est en cours sur le bouton
                        $("#sendbtn").html("Envoi en cours");
                        $("#sendbtn").addClass("btn-danger");
                        $("#sendbtn").css('cursor','progress');
                    }
                }
            }
        }

        $( "#sendbtnmail" ).click(function() {
            sendbtnmail();
        });

        function sendbtnmail() {
            var data = CKEDITOR.instances["chat_messagemail"].getData();
            var subject=$("#mailsuject").val();
            var destinataires=$("#destinataires").val();

            if(data&&subject&&!(jQuery.isEmptyObject(destinataires))) {

                try {
                    // Flager que l'envoit c'est fait
                    tosendmail=false;
                    mailto=destinataires.join(';');
                    mailto=";"+mailto;
                    $("#sendbtnmail").html("Envoyer");
                    $("#sendbtnmail").removeClass("btn-danger");
                    $("#sendbtnmail").css('cursor','auto');

                    // Push envent sur le websocket
                    event={mykey: "{{userkey}}", type: "add", message: data, mail: "true", to: mailto, subject: subject};
                    session.publish("websocket/channel/{{groupid}}", event);  
                    CKEDITOR.instances["chat_message"].setData('');

                    // Cacher la popup
                    $("#sendbymail").bootstrapSwitch('state',false);
                    $('#mymodal-sendmail').modal('hide');
                }
                catch(error) {
                    // L'envoi ne s'est pas fait
                    console.log("Retry to send");

                    // On flag le fait de retenter l'envoit à la reconnexion
                    tosendmail=true;

                    // On signal que l'envoi est en cours sur le bouton
                    $("#sendbtnmail").html("Envoi en cours");
                    $("#sendbtnmail").addClass("btn-danger");
                    $("#sendbtnmail").css('cursor','progress');
                }                

            }           
            else alert("Sujet, corps et destinataire(s) obligatoire");
        }

        $( "#sendbtnmailreply" ).click(function() {
            sendbtnmailreply();
        });

        function sendbtnmailreply() {
            var data = CKEDITOR.instances["chat_messagemail"].getData();
            var subject=$("#mailsuject").val();
            var destinataires=$("#destinataires").val();

            if(data&&subject&&!(jQuery.isEmptyObject(destinataires))) {

                try {
                    // Flager que l'envoit c'est fait
                    tosendmail=false;
                    mailto=destinataires.join(';');
                    mailto=";"+mailto;                    
                    $("#sendbtnmailreply").html("Envoyer");
                    $("#sendbtnmailreply").removeClass("btn-danger");
                    $("#sendbtnmailreply").css('cursor','auto');

                    // Push envent sur le websocket
                    id=$("#sendbtnmailreply").data("id");
                    event={mykey: "{{userkey}}", type: "reply", message: data, parent: id,  mail: "true", to: mailto, subject: subject};
                    session.publish("websocket/channel/{{groupid}}", event);  
                    CKEDITOR.instances["chat_message"].setData('');

                    // Cacher la popup
                    $("#sendbymail").bootstrapSwitch('state',false);
                    $('#mymodal-sendmail').modal('hide');
                }
                catch(error) {
                    // L'envoi ne s'est pas fait
                    console.log("Retry to send reply");

                    // On flag le fait de retenter l'envoit à la reconnexion
                    tosendmail=true;

                    // On signal que l'envoi est en cours sur le bouton
                    $("#sendbtnmailreply").html("Envoi en cours");
                    $("#sendbtnmailreply").addClass("btn-danger");
                    $("#sendbtnmailreply").css('cursor','progress');
                }                

            }           
            else alert("Sujet, corps et destinataire(s) obligatoire");
        }

        $(document).on('click', '.delmessage', function(){
            delmessage($(this).data("id"));
        });

        function delmessage(id) {
            try {
                console.log("cestk"+id);
                // Flager que l'envoit c'est fait
                todelete=false;
                idtodelete=null;

                // Push envent sur le websocket          
                event={mykey: "{{userkey}}", type: "del", id: id};
                session.publish("websocket/channel/{{groupid}}", event);              
            }
            catch(error){
                // Le delete ne s'est pas fait
                console.log("Retry to delete");                

                // On flag le fait de retenter l'envoit à la reconnexion
                todelete=true;
                idtodelete=id;
            }
        }

        $(document).on('click', '.hidemessage', function(){
            hidemessage($(this).data("id"));
        });

        function hidemessage(id) {
            $.ajax({
                method: "POST",
                url: "{{ path('cadoles_websocket_message_see') }}",
                data: {
                    id:id
                },
                success: function() {
                    $("#message-"+id).addClass ("message-see");
                    $("#hidemessage-"+id).remove();

                    if(!$("#unsee").bootstrapSwitch('state')) {
                        $("#message-"+id).hide();
                    }
                    else {
                        $("#message-"+id).show();
                    }
                }            
            }); 
        }

        $(document).on('click', '.btnreplymessage', function(){
            btnreplymessage($(this).data("id"));
        });

        function btnreplymessage(id) {
            $("#replymessage-"+id).toggle();
            $("#replymessage-"+id+" textarea").focus();
        }

        $(document).on('click', '.btnreplymessagemail', function(){
            CKEDITOR.instances["chat_messagemail"].setData("");
            $("#mailsuject").val("{{app.session.get('appname')}} = Notification {{ group.label }}");

            $("#sendbtnmail").hide();
            $("#sendbtnmailreply").show();
            $("#sendbtnmailreply").data("id",$(this).data("id"));
            $('#mymodal-sendmail').modal('show');
            $("#checkalldestinataires").prop( "checked", false );
            $("#destinataires > option").removeAttr("selected");
            $("#destinataires").trigger("change");                
            $('#destinataires').select2({
                templateResult: formatState,
                templateSelection: formatState,
                sorter: data => data.sort((a, b) => a.text.localeCompare(b.text)),
            });            
        });


        $(document).on('click', '.sendreply', function(){
            sendreply($(this).data("id"));
        });

        function sendreply(id) {
            try {
                // Flager que l'envoit c'est fait
                tosend=false;
                $("#replymessage-"+id+" a").html("Envoyer");
                $("#replymessage-"+id+" a").removeClass("btn-danger");
                $("#replymessage-"+id+" a").css('cursor','auto');

                // Push envent sur le websocket
                var data = "<p>"+$("#replymessage-"+id+" textarea").val()+"</p>";
                event={mykey: "{{userkey}}", type: "reply", message: data, parent: id};
                session.publish("websocket/channel/{{groupid}}", event);  

                $("#replymessage-"+id+" textarea").val("");
                $("#replymessage-"+id).hide();
            }
            catch(error) {
                // L'envoi ne s'est pas fait
                console.log("Retry to send");

                // On flag le fait de retenter l'envoit à la reconnexion
                tosend=true;

                // On signal que l'envoi est en cours sur le bouton
                $("#replymessage-"+id+" a").html("Envoi en cours");
                $("#replymessage-"+id+" a").addClass("btn-danger");
                $("#replymessage-"+id+" a").css('cursor','progress');
            }            
            
        }

        function recuplastmsg() {
            console.log("recuplastmsg");

            $.ajax({
                method: "POST",
                url: "{{ path('cadoles_websocket_message_list') }}",
                data: {
                    "id": {{ groupid }},
                },
                success: function(datas) {
                    $.each(datas, function(i,data) {
                        // Le message a-t-il été déposé durant la déconnexion ?
                        if(!$("#message-"+data.id).length) {
                            html ="<div id='message-"+data.id+"' class='message row message-toread'>";
                            html+="<div class='msgavatar'>";
                            html+="<img style='cursor:pointer' onclick='seeUser("+data.userid+")' id='user_avatar_img' src='/{{ alias }}/uploads/avatar/"+data.useravatar+"' class='avatar'><br>";
                            if(data.userid=={{app.user.id}} || '{{ canmanage }}'=='1') {
                                html+="<i class='delmessage fa fa-trash fa-fw' data-id='"+data.id+"' style='cursor: pointer;'></i>";
                            }
                            if (!data.havesee) {
                                html+="<i id='hidemessage-"+data.id+"' class='hidemessage fa fa-eye-slash fa-fw' data-id='"+data.id+"' title='Ne plus afficher' style='cursor: pointer;'></i>";
                            }
                            html+="</div>";
                            html+="<div class='msgdiv'>"
                            html+="<div class='msgtitle'>"+data.userlastname+"<br><small>"+new Date(data.submitdate.date).toLocaleDateString("fr-FR", dateoptions)+"</small></div>";
                            html+="<div class='msgtopic'>"+data.message+"</div>";
                            html+="<div id='msgreplys-"+data.id+"' class='msgreplys'>";
                            
                            html+="</div>";
                            html+="<a class='btnreplymessage' data-id='"+data.id+"'>Répondre</a>";
                            html+="<a class='btnreplymessagemail' data-id='"+payload.msg.id+"'>Répondre par Mail</a>";
                            html+="<div id='replymessage-"+data.id+"' class='replymessage'>";
                            html+="<textarea></textarea>";
                            html+="<a id='sendreply' class='btn btn-success sendreply' data-id='"+data.id+"'>Envoyer</a>";
                            html+="</div>";
                            html+="</div>";
                            html+="</div>";
                            $(".mychat").prepend(html);                            
                        }

                        $.each(data.childs, function(i,child) {
                            if(!$("#message-"+child.id).length) {
                                html ="<div id='message-"+child.id+"' class='message messagereply message-toread'>";
                                html+=nl2br(child.message);
                                html+="<div style='cursor:pointer' onclick='seeUser("+child.userid+")'><small>"+child.userlastname+"</small></div>";
                                html+="<small>"+new Date(child.submitdate.date).toLocaleDateString("fr-FR", dateoptions)+"</small>";
                                if(child.userid=={{app.user.id}} || '{{ canmanage }}'=='1') {
                                    html+="<i class='delmessage fa fa-trash fa-fw' data-id='"+child.id+"' title='Supprimer' style='cursor: pointer;'></i>";
                                }
                                html+="<i id='hidemessage-"+child.id+"' class='hidemessage fa fa-eye-slash fa-fw' data-id='"+child.id+"' title='Ne plus afficher' style='cursor: pointer;'></i>";
                                html+="</div>";  

                                $("#msgreplys-"+data.id).prepend(html);          
                            }
                        });                        
                    });
                } 
            });            
        }

        // islive
        function islive() {
            if(!session) return;
            isalive=true;

            {% if app.user.visible %}
            addOnline({{app.user.id}}, "{{app.user.avatar}}", "{{app.user.lastname}}", "{{app.user.firstname}}");
            
            event={mykey: "{{userkey}}", type: "islive", userid: {{app.user.id}}, useravatar: "{{app.user.avatar}}", userlastname: "{{app.user.lastname}}", userfirstname: "{{app.user.firstname}}" };
            console.log("send islive");
            session.publish("websocket/channel/{{groupid}}", event);
            {% endif %}
        }
        
        function addOnline(userid, useravatar, userlastname, userfirstname) {
            {% set colorlabel= colormain %}
            {% if border  %}
                {% set colorlabel = colorbody %}
            {% endif %}
            {% if colorbody==colorbodyfont %}
                {% set colorlabel = colorbodyback %}
            {% endif %}


            if(!$("#online"+userid).length) {
                html = "<span id='online"+userid+"' style='width:70px; display:inline-block; text-align: center; font-size: 10px; color:#{{ colorbodyback }}; text-transform: uppercase; line-height:11px;overflow-wrap: break-word;vertical-align:top;'>";
                html+= "<img style='cursor:pointer; width:40px; height:40px; margin-bottom:5px;' onclick='seeUser("+userid+")' title='"+userlastname+" "+userfirstname+"' id='user_avatar_img' src='/{{ alias }}/uploads/avatar/"+useravatar+"' class='avatar'>";
                html+= "<br><span style='color:#{{colorlabel}}'>"+userlastname+" "+userfirstname+"</span>";
                html+= "</span>";
                $("#useronline").append(html);
            }
        }
      

    {% endif %}  

{% endblock %}