const pratech = {};
pratech.parly = {
  url: "https://parly-webchat-comultrasan-fibotclientes.1jp71cao1my3.us-east.codeengine.appdomain.cloud",
  customer_public: "comultrasan",
  src: null,
  data: { token: null, userId: null, expires_in: null },
  directLineSecret: null,
  botConnection: null,
  userBot: null,
  
  getUrlBaseJS: function () {
    return pratech.parly.url + "/" + pratech.parly.customer_public + "/js/";
  },


  getUrlBaseStyles: function () {
    return pratech.parly.url + "/" + pratech.parly.customer_public + "/css/";
  },

  getUrlBaseImages: function () {
    return pratech.parly.url + "/" + pratech.parly.customer_public + "/images/";
  },
  /**
   * funcion base carga script
   */
  getScript: function (source, callback) {
    let script = document.createElement("script");
    let prior = document.getElementsByTagName("script")[0];
    script.async = 1;

    script.onload = script.onreadystatechange = function (_, isAbort) {
      if (
        isAbort ||
        !script.readyState ||
        /loaded|complete/.test(script.readyState)
      ) {
        script.onload = script.onreadystatechange = null;
        script = undefined;
        if (!isAbort)
          if (callback) callback();
      }
    };

    script.src = source;
    prior.parentNode.insertBefore(script, prior);
  },

  _consultarConfiguraciones: function () {
    let urlBase = pratech.parly.url + "/api/v2/rest/bots/tokens/generate";

    jqchat.get(urlBase, function (data) {
      pratech.parly.data = data;
    }).fail(function (error) {
      console.log("get", error);
    })
  },

  _schedule_refresh_token: function () {
    const milliseconds = pratech.parly._calculate_timer();
    setTimeout(function () {
      pratech.parly._refresh_token();
    }, milliseconds);
  },

  _calculate_timer: function () {
    let milliseconds = 0;
    if (pratech.parly.data && pratech.parly.data.expires_in) {
      milliseconds = 900000;
    }
    return milliseconds;
  },

  _refresh_token: function () {

    if (pratech.parly.data && pratech.parly.data.token) {
      $.ajax({
        url: pratech.parly.url + "/api/token/refresh",
        data: {
          token: pratech.parly.data.token
        },
        // xhrFields: { withCredentials: true },
        method: "POST",
        dataType: "json",
        success: function (newData) {
          pratech.parly.data = newData;
          pratech.parly._schedule_refresh_token();
        }
      });
    } else {
      console.log("Error, no hay datos para refrescar.");
    }


  },

  initChat: function () {
    jqchat(document).ready(function () {
      pratech.parly._injectReferences();
      pratech.parly._consultarConfiguraciones();
      pratech.parly._eventosChat();
    });
  },

  _eventosChat: function () {
    jqchat(".chat").click(function () {
      pratech.parly._openchatbox();
    });

    jqchat(".hide-chat").click(function () {
      pratech.parly._hidechatbox();
    });

    jqchat(".expand-chat").click(function () {
      pratech.parly._expandchatbox();
    });
  },

  _expandchatbox: function () {
    jqchat(".expand-chat").toggleClass("active");
    jqchat(".chatbot-pratech-main").toggleClass("expanded-chatbot-pratech");
  },

  _hidechatbox: function () {
    jqchat(".chatbot-pratech-main").removeClass("show");
    jqchat(".chat").click(function () {
      pratech.parly._openchatbox();
    });
  },

  _hideImageContent: function () {
    jqchat(".chatbot-fullscreen-pratech").fadeOut(200, function () {
      jqchat(this).removeClass("show");
      jqchat(".fullscreen-pratech-content > img").remove();
      pratech.parly.src = null;
    });
  },

  _openchatbox: function () {
    if (jqchat(".chatbot-parent-draggable-pratech.parent").length) {
      jqchat(".chatbot-pratech-main").addClass("show");
    } else {

      if (typeof BotChat !== "undefined" && BotChat && pratech.parly.data && pratech.parly.data.token) {
        jqchat("body").append(
          jqchat(
            '<div class="chatbot-parent-draggable-pratech parent"></div>' +
            '<div class="chatbot-pratech-main show" id="draggable">' +
            '<div class="chatbot-pratech-content">' +
            '<div class="chatbot-pratech-header">' +
            '<div class="chatbot-pratech-info-title">' +
            '<div class="chatbot-pratech-title-chat">¡Hola, soy Fibot!</div>' +
            '<p class="chatbot-pratech-p1">Asistente virtual de Financiera Comultrasan</p>' +
            '<div class="chatbot-pratech-actions">' +
            '<ul class="chatbot-pratech-list-actions">' +
            '<li><a href="javascript:;" class="hide-chat"><i class="fa fa-times"></i></a></li>' +
            '<li><a href="javascript:;" class="expand-chat"></a></li>' +
            "</ul>" +
            "</div>" +
            '<div class="chatbot-pratech-logo">' +
            '<img src="' +
            pratech.parly.getUrlBaseImages() +
            'chatbot-pratech-logo.png" alt="" class="img-responsive">' +
            "</div>" +
            "</div>" +
            "</div>" +
            '<div class="chatbot-pratech-body">' +
            '<div class="chatbot-pratech-container">' +
            '<div class="chatbot-pratech-bot" id="bot"></div>' +
            "</div>" +
            "</div>" +
            "</div>" +
            "</div>"
          )
        );

        if (!pratech.parly.userBot) {
          pratech.parly.userBot = {
            id: pratech.parly.data.userId,
            name: ''
          };

          pratech.parly.directLineSecret = pratech.parly.data.token;

          pratech.parly.botConnection = new BotChat.DirectLine({
            token: pratech.parly.directLineSecret
          });

          BotChat.App({
            botConnection: pratech.parly.botConnection,
            user: pratech.parly.userBot,
            bot: {
              id: "botid"
            },
            resize: "detect"
          },
            document.getElementById("bot")
          );

          jqchat(".hide-chat").click(function () {
            pratech.parly._hidechatbox();
          });

          jqchat(".expand-chat").click(function () {
            pratech.parly._expandchatbox();
          });


          jqchat("#draggable").draggable({
            containment: '.chatbot-parent-draggable-pratech',
            handle: '.chatbot-pratech-header',
            scroll: false,
          });

          pratech.parly._calculate_timer();
          pratech.parly._saludar();

        }

      }
    }
  },

  _saludar: function () {
    let saludo = jqchat(".chat.chatbot-pratech-floating").attr("saludo") || "Hola";
    pratech.parly._botStart(saludo);
  },

  _botStart: function (saludo) {
    pratech.parly.botConnection
      .postActivity({
        type: "message",
        from: {
          id: pratech.parly.userBot.id,
          name: pratech.parly.userBot.name
        },
        text: saludo
      })
      .subscribe(function (id) {
        console.log("success", id);
      });

    this.botConnection.activity$
      .filter(function (activity) {
        pratech.parly._lastMessage(activity);
      })
      .subscribe(function (activity) {
        console.log("subscribe", activity);
      });
  },

  _lastMessage: function (activity) {
    if (activity && activity.type == "typing") {
      jqchat(".wc-message-wrapper")
        .last()
        .addClass("wc-pratech-typing");
      jqchat(".pratech-typing").addClass("show");
    } else {
      jqchat(".wc-message-wrapper").removeClass("wc-pratech-typing");
      jqchat(".wc-message-groups").animate({
        scrollTop: jqchat(".wc-message-group-content").height()
      },
        0
      );
      jqchat(".pratech-typing").removeClass("show");
    }
  },

  _imageMessage: function (activity) {
    if (activity && activity.type == "message") {
      if (activity.attachments) {
        if (activity.attachments[0].content.images) {
          jqchat(".wc-card.hero > img").click(function () {
            if (!pratech.parly.src) {
              pratech.parly.src = activity.attachments[0].content.images[0].url;
              pratech.parly._openImage();
            }
            jqchat(".close-fullscreen").click(function () {
              pratech.parly._hideImageContent();
            });
          });
        }
      }
    }
  },

  _openImage: function () {
    if (jqchat(".chatbot-fullscreen-pratech").length) {
      jqchat(".fullscreen-pratech-content").append(
        jqchat('<img src="' + pratech.parly.src + '">')
      );
      jqchat(".chatbot-fullscreen-pratech").addClass("show");
    } else {
      jqchat("body").append(
        jqchat(
          '<div class="chatbot-fullscreen-pratech show">' +
          '<div class="chatbot-fullscreen-pratech-content">' +
          '<div class="fullscreen-pratech-body">' +
          '<button type="button" class="close-fullscreen">' +
          '<span class="fa fa-times"></span>' +
          "</button>" +
          '<div class="fullscreen-pratech-content">' +
          '<img src="' +
          pratech.parly.src +
          '">' +
          "</div>" +
          "</div>" +
          "</div>" +
          "</div>"
        ).fadeIn(200)
      );
    }
  },

  _injectReferences: function () {
    //Css bot framework
    jqchat("head").append(
      jqchat('<link rel="stylesheet" type="text/css" />').attr(
        "href",
        pratech.parly.getUrlBaseStyles() + "botchat.css"
      )
    );
    $("head").append(
      $('<link rel="stylesheet" type="text/css" />').attr(
        "href",
        pratech.parly.getUrlBaseStyles() + "styles.css"
      )
    );

    //Js bot framework
    //js font awesome
    jqchat
      .ajax({
        url: 'https://use.fontawesome.com/de8656cdb1.js',
        dataType: 'script',
        cache: true
      })
      .done(function (script, textStatus) {
        console.log('load  https://kit.fontawesome.com/43f6fd71af.js');
      });

    jqchat
      .ajax({
        url: pratech.parly.getUrlBaseJS() + "botchat.js",
        dataType: "script",
        cache: true
      })
      .done(function (script, textStatus) {
        console.log("load botchat.js");
      });

    jqchat
      .ajax({
        url: pratech.parly.getUrlBaseJS() + "jqchat.ui.min.js",
        dataType: "script",
        cache: true
      })
      .done(function (script, textStatus) {
        console.log(
          "load jquery.ui.jqchat.js"
        );
      });
  },

  _guid: function () {
    function s4() {
      return Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1);
    }
    return (
      s4() +
      s4() +
      "-" +
      s4() +
      "-" +
      s4() +
      "-" +
      s4() +
      "-" +
      s4() +
      s4() +
      s4()
    );
  }
};

document.addEventListener("DOMContentLoaded", function () {
  pratech.parly.getScript(
    pratech.parly.getUrlBaseJS() + "jqchat.min.js",
    function () {
      pratech.parly.initChat();
    }
  );
});