"use strict";

/**
 * Ventanas de chat que se abren al hacer click a un usuario
 */

let ChatBox = function (item) {
    this.item = item;
    this.created_at = Chat.time(); // para sort

    this.displayed = true; // por defecto cada chat creado se muestra
    this.hidden = false; // chatbox hidden

    this.flash = false;
    this.flash_step = 0;

    this.typing = false;

    this.html = null;

    this.evalUnread();
}

ChatBox.prototype.isChatBox = function () {
    return !this.item ? false : true;
}

ChatBox.prototype.getId = function () {
    return this.item.id;
}

ChatBox.prototype.getName = function () {
    return this.item.name;
}

ChatBox.prototype.getUnread = function () {
    if (this.isChatBox()) {
        return this.item.unread;
    }
    else {
        return 0;
    }
}

ChatBox.prototype.flashStart = function () {

    if (this.flash !== false) {
        clearInterval(this.flash);
        this.flash = false;
    }

    let self = this;
    this.flash = setInterval(function () {
        let color = self.html.find('.me-chat-box-header').css('background-color');

        if (self.flash_step) {
            self.html.find('.me-chat-box-header').css('background-color', Chat.box_color());
            self.flash_step = 0;
        }
        else {
            self.html.find('.me-chat-box-header').css('background-color', Chat.box_alert_header_flash_color());
            self.flash_step = 1;
        }

    }, 1000);
}

ChatBox.prototype.flashStop = function () {

    if (this.flash !== false) {
        clearInterval(this.flash);
        this.flash = false;

        this.flash_step = 0;
        this.html.find('.me-chat-box-header').css('background-color', Chat.box_color());
    }
}

/**
 * Muestra/minimiza el chat
 * Se ejecuta al hacer click en el header del chat
 */
ChatBox.prototype.toogleShow = function () { console.log("ChatBox.toogleShow()");

    // si esta oculto, lo mostramos
    if (this.hidden) { //console.log("is hidden,  making show")
        this.hidden = false;
        this.html.removeClass('me-chat-box-hidden');
    }
    else { //console.log("is show,  making hidde")
        this.hidden = true;
        this.html.addClass('me-chat-box-hidden');
    }
}

ChatBox.prototype.isHidden = function () {
    return this.hidden;
}

ChatBox.prototype.isDisplayed = function () {
    return this.displayed;
}

ChatBox.prototype.displayedOn = function () {
    this.created_at = Time.segundos();
    this.displayed = true;
    this.html.show();
}

ChatBox.prototype.displayedOff = function () {
    this.displayed = false;
    this.html.hide();
}

ChatBox.prototype.hasFocus = function() {
    if ($(this.html).find('.me-chat-box-body-submit input').is(':focus')) {
        console.log('hasfocus');
        return true;
    }
    else {
        console.log('no hasfocus');
        return false;
    }
}

// add a time separator inside body of the chat
ChatBox.prototype.timeSeparator = function(fecha, is_old) { //console.log('timeSeparator()' + fecha + "|" + this.item.lastmessage.fecha);
    let f1 = Time.fecha("DD/MM/YYYY h:mm", fecha); //console.log(f1);
    let f2 = Time.fecha("DD/MM/YYYY h:mm", this.item.lastmessage.fecha); //console.log(f1);
    // si es la misma fecha que el mensaje anterior, no se hace nada
    if (!this.item.lastmessage.fecha || f1 == f2) {
        return;
    }


    fecha = Time.formatChatTimeFecha(fecha);
    let chatDOM_content = this.html.find('.me-chat-box-body-content');

    // remover fechas repetidas
    let timeSeparators = $(chatDOM_content).find('*:contains("' + fecha + '")');
    if ($(timeSeparators).is('.me-chat-box-message-timeseparator')) {
        $(timeSeparators).remove();
    }

    if (is_old === true) {
        $('<div class="me-chat-box-body-content-message"><div class="me-chat-box-message-timeseparator">' + fecha + '</div></div>').prependTo(chatDOM_content);
    }
    else {
        $('<div class="me-chat-box-body-content-message"><div class="me-chat-box-message-timeseparator">' + fecha + '</div></div>').appendTo(chatDOM_content);
    }
}

// checa mensajes sin leer
ChatBox.prototype.evalUnread = function () { console.log("ChatBox.evalUnread()");
    if (this.item.unread > 0) {
        if  (this.item.lastmessage.sender == this.item.id) {
            this.flashStart();
        }
    }
}

ChatBox.prototype.setOnline = function () { console.log("ChatBox.setOnline()");
    $(this.html).find('.me-chat-box-header-status').removeClass('offline away').addClass('online');
}

ChatBox.prototype.setOffline = function () { console.error("ChatBox.setOffline()");
    $(this.html).find('.me-chat-box-header-status').removeClass('online away').addClass('offline');
}

ChatBox.prototype.setAway = function () { console.log("ChatBox.setAway");
    $(this.html).find('.me-chat-box-header-status').removeClass('online offline').addClass('away');
}

ChatBox.prototype.setTyping = function () { console.log("ChatBox.setTyping");

    if (this.typing !== false) {
        clearTimeout(this.typing);
        this.typing = false;
    }

    $(this.html).find('.me-chat-box-message-sent-seen').text('Está escribiendo...');

    let self = this;
    this.typing = setTimeout(function () {
        $(self.html).find('.me-chat-box-message-sent-seen').text('');
    }, 3000);
}

ChatBox.prototype.setTypingOff = function () { //console.log("ChatBox.setTypingOff");
    if (this.typing !== false) {
        clearTimeout(this.typing);
        this.typing = false;
    }
}
/**
 * Agrega un mensaje al chatbox
 */
ChatBox.prototype.recv = function (msg) { console.log("ChatBox.recv() id:"+this.item.id + " selfid:"+Vendedor.getId());
    this.setTypingOff();
    this.drawMessage(msg);
    this.scrollToBottom();

    // si quien envio el mensaje es la otra persona, mostramos notificacion de audio
    if (msg.isNotSelf()) { console.warn("PLAY")
        let sound = new Audio('/js/chat/sounds/' + Chat.soundFile());
        sound.play();

        if (this.hasFocus()) {
            Server.sendChatLeido(msg.getFriendId());
        }
        else {
            this.item.unread += 1;
            this.evalUnread();
            this.item.evalOpened();
            Server.sendChatDelivered(msg.getFriendId);
        }
    }
    else {

    }
}

// crea html para mensaje enviado
ChatBox.prototype.sendDOMMessage = function(message, oldmessages) { //console.log("ChatBox.sendDOMMessage(): " + message)

    let chatDOM_content = this.html.find('.me-chat-box-body-content');

    let returnDOM = false;
    if (oldmessages === true) {
        returnDOM = $('<div class="me-chat-box-body-content-message"><div class="me-chat-box-message-sent" style="background-color: ' + Chat.box_color_sent_background() + '; color: ' + Chat.box_color_sent_text() + ';">' + Chat.msgHtml(message) + '</div></div>').prependTo(chatDOM_content);
    }
    else {
        returnDOM = $('<div class="me-chat-box-body-content-message"><div class="me-chat-box-message-sent" style="background-color: ' + Chat.box_color_sent_background() + '; color: ' + Chat.box_color_sent_text() + ';">' + Chat.msgHtml(message) + '</div></div>').appendTo(chatDOM_content);
    }

    // Message with image
    if ($(returnDOM).find('.me-chat-box-message-image').length == 1) {
        $(returnDOM).find('.me-chat-box-message-sent').addClass('me-chat-box-message-with-oneimage');
    }
    else if ($(returnDOM).find('.me-chat-box-message-image').length > 1) {
        $(returnDOM).find('.me-chat-box-message-sent').addClass('me-chat-box-message-with-image');
    }

    // Message with youtube video
    if ($(returnDOM).find('.me-chat-box-message-youtube').length == 1) {
        $(returnDOM).find('.me-chat-box-message-sent').addClass('me-chat-box-message-with-oneyoutube');
    }
    else if ($(returnDOM).find('.me-chat-box-message-youtube').length > 1) {
        $(returnDOM).find('.me-chat-box-message-sent').addClass('me-chat-box-message-with-youtube');
    }

    return returnDOM; // Return DOM element of the message
}

// crea html para mensaje recibido
ChatBox.prototype.receiveDOMMessage = function(message, oldmessages) { //console.log("ChatBox.receiveDOMMessage(): " + message)

    let chatDOM_content = this.html.find('.me-chat-box-body-content');

    let returnDOM = false;
    if (oldmessages === true) {
        returnDOM = $('<div class="me-chat-box-body-content-message"><div class="me-chat-box-message-received-userpicture" style="background-image: url('+ this.item.pic +')"></div><div class="me-chat-box-message-received" style="background-color: ' + Chat.box_color_received_background() + '; color: ' + Chat.box_color_received_text() + ';">' + Chat.msgHtml(message) + '</div></div>').prependTo(chatDOM_content);
    }
    else {
        returnDOM = $('<div class="me-chat-box-body-content-message"><div class="me-chat-box-message-received-userpicture" style="background-image: url('+ this.item.pic +')"></div><div class="me-chat-box-message-received" style="background-color: ' + Chat.box_color_received_background() + '; color: ' + Chat.box_color_received_text() + ';">' + Chat.msgHtml(message) + '</div></div>').appendTo(chatDOM_content);
    }

    // Message with image
    if ($(returnDOM).find('.me-chat-box-message-image').length == 1) {
        $(returnDOM).find('.me-chat-box-message-received').addClass('me-chat-box-message-with-oneimage');
    }
    else if ($(returnDOM).find('.me-chat-box-message-image').length > 1) {
        $(returnDOM).find('.me-chat-box-message-received').addClass('me-chat-box-message-with-image');
    }

    // Message with youtube video
    if ($(returnDOM).find('.me-chat-box-message-youtube').length == 1) {
        $(returnDOM).find('.me-chat-box-message-received').addClass('me-chat-box-message-with-oneyoutube');
    }
    else if ($(returnDOM).find('.me-chat-box-message-youtube').length > 1) {
        $(returnDOM).find('.me-chat-box-message-received').addClass('me-chat-box-message-with-youtube');
    }

    return returnDOM;
}

// agrega un mensaje en el html del chatbox
// llamado al abrir el chat y al cargar mensajes anteriores
ChatBox.prototype.drawMessage = function (message, oldmessages) { //console.log('ChatBox.drawMessage()');

    // separa los mensajes por fecha
    this.timeSeparator(message.fecha, oldmessages);

    // actualizamos ultimo mensaje
    this.item.lastmessage = message;
    this.item.lastupdate = Chat.time();

    let returnDOM = false;

    // enviado
    if (message.isSelf()) {
        returnDOM = this.sendDOMMessage(message.getMessage(), oldmessages);
        //$(returnDOM).append('<div class="me-chat-box-message-popover"><div class="me-chat-box-message-popover-caretleft"></div><div class="me-chat-box-message-popover-content">' + message.getDate() + '</div></div>');
        //$(returnDOM).prepend('<div class="me-chat-box-message-sent-date">' + message.getDate() + '</div>');

        if (message.isRead()) {
            $(returnDOM).append('<div class="me-chat-box-message-sent-seen">Visto</div>');
        }
        else if (message.isDelivered()) {
            $(returnDOM).append('<div class="me-chat-box-message-sent-seen">Recibido</div>');
        }
        else {
            $(returnDOM).append('<div class="me-chat-box-message-sent-seen"></div>');
        }
    }
    // recibido
    else {
        returnDOM = this.receiveDOMMessage(message.getMessage(), oldmessages);

        //$(returnDOM).append('<div class="me-chat-box-message-popover"><div class="me-chat-box-message-popover-caretright"></div><div class="me-chat-box-message-popover-content">' + message.getDate() + '</div></div>');
        //$(returnDOM).prepend('<div class="me-chat-box-message-received-date">' + message.fecha + '</div>');
        $(returnDOM).append('<div class="me-chat-box-message-sent-seen"></div>');
    }

    return returnDOM;
}

// scroll to the bottom
ChatBox.prototype.scrollToBottom = function() {
    let chatDOM_content = this.html.find('.me-chat-box-body-content');
    let height = chatDOM_content[0].scrollHeight;
    chatDOM_content.scrollTop(height);
}

// cuando se hace click en el area de mensajes
ChatBox.prototype.clickInside = function () { console.log("ChatBox.clickInside()");

    $(this.html).find('input').focus();

    if (this.isChatBox()) {
        this.flashStop();

        // detenemos flashing
        if (this.item.unread > 0) {
            this.item.unread = 0;
            this.evalUnread();
            this.item.evalOpened();

            // notificamos de mensaje leido
            soc.send({
                'action':'CHAT_LEIDO',
                'sender': this.item.id,
                'sender_type': this.item.type
            });
        }
    }
}

ChatBox.prototype.setLeido = function () {
    $(this.html).find('.me-chat-box-message-sent-seen').text('Visto');
}


ChatBox.prototype.setRecibido = function () {
    $(this.html).find('.me-chat-box-message-sent-seen').text(' ');
}


ChatBox.prototype.send = function (message) {
    Server.sendChat(message,this.item.id);
}

ChatBox.prototype.sendTyping = function () {
    Server.sendChatTyping(this.item.id);
}

ChatBox.prototype.close = function () { console.log("ChatBox.close()");
    this.html.remove();
}