let Server = (function () {
    "use strict";

    let soc;
    let is_kill = false;
    let is_chat_typing = false;

    let start = function() { console.log("Server.start()");
        if (soc == null) {
            soc = new SocClient(this);
        }

        soc.connect();
    }

    let getIp = function () {
        return "209.182.203.240";
    }

    let getPort = function () {
        return 17000;
    }

    let getDeviceId = function () {
        return soc.getDeviceId();
    }

    let close = function () {
        is_kill = true;
        soc.close();
    }

    let canSend = function() {
        if (!soc.isConnected()) {
            ui.loadingStop();
            ui.dialogErrorSimple(_t('socket_not_connected'));
            soc.connect();
            return false;
        }

        return true;
    }

    let sending = function(data, msg) {
        if (canSend()) {
            ui.loadingStart(!msg?_t('consultando'):msg);
            soc.send(data);
        }
    }

    let send = function(data) { //console.log("Server.send(): " + JSON.stringify(data));
        if (canSend()) {
            soc.send(data);
        }
    }

    let sendChat = function(message, friendId) {
        send({
            'action': packet.CHAT,
            'receiver': friendId,
            'message': message,
            'type': Co.MSG_TYPE_TEXT
        });
    }

    let sendChatLeido = function(friendId) {
        send({
            'action': packet.CHAT_LEIDO,
            'friendId': friendId,
        });
    }

    let sendChatDelivered = function(friendId) {
        send({
            'action': packet.CHAT_DELIVERED,
            'friendId': friendId,
        });
    }

    let sendChatTyping = function(friendId) {
        if (is_chat_typing) {
            return;
        }

        is_chat_typing = true;

        send({
            'action': packet.CHAT_TYPING,
            'friendId': friendId,
        });

        setTimeout(function () {
            is_chat_typing = false;
        },3000);
    }

    let onConnect = function(data) { //console.log("Server.onConnect()");
        if (data.ismulti) {
            $('#input-login-id').show();
        }
        else {
            $('#input-login-id').hide();
        }

        if (is_kill) {
            is_kill = false;
            return;
        }

        LoginActivity.autoLogin();
    }

    let onMessage = function (msg) { //console.log("Server.onMessage()"); console.log(msg);
        if (msg.msg) {
            msg.msg = msg.msg.replace(/\n/g, "<br />");
        }

        api[msg.action](msg);
    }

    let onConnectionLost = function() { //console.log("Server.onConnectionLost()");

        /*// si ya hay un proceso de conexion, no ejecutamos
        if (connecting) { return; }
        connecting = true;

        // se muestra el modal
        box_connection_lost.show();

        percent = 0;
        reconnect();*/
    };

    let configEmpresa = function (codigo) { console.log("Server.configEmpresa()");
        if (codigo) {
            Server.sending({
                "action": packet.REGISTER_DEVICE,
                "key": codigo
            });
            return;
        }

        $.confirm({
            title: 'Registrar Terminal',
            content: '' +
            '<form action="" class="formName">' +
            '<div class="form-group">' +
            '<label>Escriba el código</label>' +
            '<input type="text" class="codigo form-control" maxlength="12" required />' +
            '</div>' +
            '</form>',
            buttons: {
                formSubmit: {
                    text: 'Aceptar',
                    btnClass: 'btn-blue',
                    action: function () {
                        let codigo = this.$content.find('.codigo').val();
                        if(codigo.length != 12) {
                            $.alert('Escriba un código válido');
                            return false;
                        }

                        Server.sending({
                            "action": packet.REGISTER_DEVICE,
                            "key": codigo
                        });
                    }
                },
                cancel: function () {},
            },
            onContentReady: function () {
                let jc = this;
                this.$content.find('form').on('submit', function (e) {
                    e.preventDefault();
                    jc.$$formSubmit.trigger('click');
                });
            }
        });
    }

    return {
        close: close,
        sendChat: sendChat,
        sendChatLeido: sendChatLeido,
        sendChatDelivered: sendChatDelivered,
        sendChatTyping: sendChatTyping,
        start: start,
        send: send,
        sending: sending,
        onConnect: onConnect,
        onConnectionLost: onConnectionLost,
        onMessage: onMessage,
        getDeviceId: getDeviceId,
        getIp: getIp,
        getPort: getPort,
        configEmpresa: configEmpresa,
        appVersion: function () {
            return soc.getVersion();
        },

        server_port: 17000,
        url_update_check: "/app/checkupdate",
        url_update: "/app/getapk",
        url_upload_avatar: "/app/upload_avatar",
        url_upload_sound: "/app/upload_sound",
        url_upload_image: "/app/upload_image",
        url_download_avatar: "/app/download_avatar",
        url_download_sound: "/app/download_sound",
        url_download_image: "/app/download_image",
        url_chat_delete: "/app/chat_delete"
    }
}());