var chatBox;
var chatBoxFocusFlg = 1;
var chatBotSocket;

function chatBoxInit(obj){
  chatBox = new Chat(obj);
}

class Chat {
  constructor(obj) {
    this.chatSocketUrl = `wss://chat.gclub.casino`;
    this.chatWebUrl = `https://chat.gclub.casino`;
    this.chats = {};
    this.chatUnreads = [];

    this.chatBoxTitle = obj.chatBoxTitle ?? 'Chat with us';
    this.chatBoxTheme = obj.chatBoxTheme ?? 'gold';
    this.token = obj.token;
    this.chatId = obj.chatId;
    this.chatKey = obj.chatKey;
    this.userKey = obj.userKey;
    this.userName = obj.userName;
    this.userType = "USER";

    this.init();
  }

  init() {
    document.head.innerHTML += `<link rel="stylesheet" href="${this.chatWebUrl}/assets/css/style.${this.chatBoxTheme}.css">`;
    document.head.innerHTML += `<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">`;
    document.body.innerHTML += `<div class="chatbox chatbox22 chatbox-tray">
        <div class="chatbox_title">
          <h5><a href="javascript:void(0);">${this.chatBoxTitle}</a><span id="chat_notification_count" class="noti_count" style="display:none;"></span></h5>
          <!--<button class="chatbox_title_tray">
              <span></span>
          </button>-->
          <button class="chatbox_title_close"> <span>
          <svg viewBox="0 0 12 12" width="12px" height="12px">
            <line stroke="#FFFFFF" x1="11.75" y1="0.25" x2="0.25" y2="11.75"></line>
            <line stroke="#FFFFFF" x1="11.75" y1="11.75" x2="0.25" y2="0.25"></line>
          </svg>
          </span> </button>
        </div>
        <div class="chatbox_body" id="chatbox_body">
        </div>
        <div style="display:none;">
          <form id="chat_send_image_form">
            <input type="file" id="chat_input_image" name="image" onchange="chatBox.sendImage();" accept="image/png, image/gif, image/jpeg">
          </form>
        </div>
        <div class="panel-footer">
          <div class="input-group-send">            
            <input id="chat_message_input" type="text" class="form-control input-sm chat_set_height" placeholder="Type your message here..." tabindex="0" dir="ltr" spellcheck="false" autocomplete="off" autocorrect="off" autocapitalize="off" contenteditable="true" />
            <span class="input-group-send-btn">
            <button class="btn bt_bg cb-btn-chat" id="chat_send_text_btn">Send</button>
            </span> </div>
            <a id="chat_send_image_btn" class="btn-image"><i class="fa-solid fa-image"></i></a>
            <!-- <a id="" class="btn-image"><i class="fa-solid fa-face-smile"></i></a> -->
        </div>
      </div>`;

    var $chatbox = $('.chatbox');
    var $chatboxTitle = $('.chatbox_title');
    $chatboxTitle.on('click', function () {
      $chatbox.toggleClass('chatbox-tray');
      if(!$chatbox.hasClass('connected')){
        $chatbox.addClass('connected');
        chatBox.connect();
      }
      var messages = document.getElementById('chatbox_body');
      messages.scrollTop = messages.scrollHeight; 
    });

    if(this.userKey.toString().search(/^MEMBER_/)>=0){
      setTimeout(function(){
        $chatbox.addClass('connected');
        chatBox.connect();
      },600);
    }
  }

  connect() {
    const chatWebUrl= this.chatWebUrl;
    document.getElementById('chatbox_body').innerHTML = "";

    chatBotSocket = new WebSocket(`${this.chatSocketUrl}/chat/${this.chatId}/${this.chatKey}?token=${this.token}&userType=${this.userType}&userKey=${this.userKey}&userName=${this.userName}`);

    chatBotSocket.onopen = function () {
      console.log('WebSocket connection established');
    };
    
    chatBotSocket.onmessage = function (event) {
      var data = JSON.parse(event.data);
      
      if (data.cmd === "chat_receive") {
          chatBox.chatUpdate(data.data);

          if(data.data.userRead!="1"){
            if(!chatBox.chatUnreads.includes(data.data.messageId)) chatBox.chatUnreads.push(data.data.messageId);

            $('#chat_notification_count').text(chatBox.chatUnreads.length)
            if(chatBox.chatUnreads.length>0){
              $('#chat_notification_count').show();
            }else{
              $('#chat_notification_count').hide();
            }

            if(chatBoxFocusFlg==1 && !$chatbox.hasClass('chatbox-tray')){
              chatBox.chatRead()
            }
          }
      }
    };

    chatBotSocket.onerror = function (error) {
      console.error('WebSocket error observed:', error);
    };

    chatBotSocket.onclose = function (event) {
      if (!event.wasClean) {
        console.log(`WebSocket closed unexpectedly: code=${event.code}, reason=${event.reason}`);
      }
      setTimeout(connect, 1000);
    };
  }

  chatRead(){
    while(chatBox.chatUnreads.length>0){
      var messageId = chatBox.chatUnreads.shift();
      var message = JSON.stringify({
        cmd: 'chat_read',
        messageId: messageId,
      });
      chatBotSocket.send(message);
    }

    $('#chat_notification_count').text(chatBox.chatUnreads.length)
    if(chatBox.chatUnreads.length>0){
      $('#chat_notification_count').show();
    }else{
      $('#chat_notification_count').hide();
    }
  }

  chatUpdate(data){
    chatBox.chats[data.messageId] = data;
    chatBox.chats = Object.keys(chatBox.chats).sort().reduce(
        (obj, key) => { 
            obj[key] = chatBox.chats[key]; 
            return obj;
        }, 
        {}
    );
    chatBox.renderChat();
  }

  renderChat(){
    var messages = document.getElementById('chatbox_body');
    const chatWebUrl = chatBox.chatWebUrl;

    $('#chatbox_body').html('');
    var userKeyPrev = '';
    var datePrev = '';

    for(var messageId in chatBox.chats){
      var item = chatBox.chats[messageId];
      var html = "";

      var messageClass = item.userType === 'AGENT' ? 'chatbox_body_message_right' : 'chatbox_body_message_left';
      var readHtml = item.userType === 'USER' && item.agentRead=="1" ? '<i class="fa-solid fa-circle-check"></i>' : '';

      var createdDate = new Date(item.createdDate);
      var dateText = createdDate.getFullYear().toString()+"-"+
      ("0"+(createdDate.getMonth()+1).toString()).substr(-2)+"-"+
      ("0"+createdDate.getDate().toString()).substr(-2);
      var timeText = ("0"+createdDate.getHours().toString()).substr(-2)+":"+
      ("0"+createdDate.getMinutes().toString()).substr(-2);

      if(datePrev!=dateText){
        html += `<div class="chatbox_dating">${dateText}</div><div class="chatbox_body_message"></div>`;
      }

      var message = "";
      if (item.type === "TEXT") {
        message = item.data;//item.replace(/(<([^>]+)>)/gi, "");
        
      }
      if (item.type === "IMAGE") {
        var data = JSON.parse(item.data,true);
        message = `<a href="${chatWebUrl}/${data.fileUrl}" target="_blank"><img src="${chatWebUrl}/${data.thumbnailUrl}"/></a>`;
        messageClass +=  ' chatbox_body_message_img';
      } 
      

      html += `<div class="chatbox_body_message ${messageClass}">
            <div class="ul_section_full">
              <div class="ul_msg">${message}</div>
              <div class="clearfix"></div>
            </div>
            <div class="chatbox_timing">${readHtml} ${timeText}</div>
            </div>`;

      $('#chatbox_body').append(html)
      datePrev = dateText;
    }  
    messages.scrollTop = messages.scrollHeight;  
  }

  send(type, data) {
    var message = {
      cmd: "chat_send",
      userKey: this.userKey,
      userName: this.userName,
      userType: this.userType,
      type: type,
      data: data,
    };
    chatBotSocket.send(JSON.stringify(message));
  }

  sendImage() {
    var fileInput = document.getElementById('chat_input_image');
    if (fileInput.files.length > 0) {
        var file = fileInput.files[0];
        var reader = new FileReader();

        reader.onload = function (e) {
            var base64Data = e.target.result;
            var message = {
                cmd: "chat_send",
                userKey: chatBox.userKey,
                userName: chatBox.userName,
                userType: chatBox.userType,
                type: "IMAGE",
                data: base64Data.split(',')[1],
            };
            chatBotSocket.send(JSON.stringify(message));
        };

        reader.onerror = function (e) {
            console.error("Error reading file:", e);
        };

        reader.readAsDataURL(file);
    } else {
        console.error("No file selected");
    }
  }
}

$(document).on('click','#chat_send_image_btn',function() {
  $('#chat_send_image_form #chat_input_image').click();
})

$(document).on('click', '#chat_send_text_btn', function () {
  var message = $('#chat_message_input').val().trim();
  if (message !== "") {
    chatBox.send("TEXT", message);
    $('#chat_message_input').val('');
  }
})

$(document).on('keypress', '#chat_message_input', function (e) {
  if(e.which==13){
    var message = $('#chat_message_input').val().trim();
    if (message !== "") {
      chatBox.send("TEXT", message);
      $('#chat_message_input').val('');
    }
  }
})

$(window).blur(function() {
  chatBoxFocusFlg = 0;
});

$(window).focus(function() {
  chatBoxFocusFlg = 1;
  chatBox.chatRead();
});