// activity start

var secondsSinceLastActivity = 0;
var displayActivity = 0;
var activityValue;
var chatOpen = false;
var textContents = [
  "Hello how are you doing?",
  "Hi i'm Jackie how can i help you?",
  "Im a bot. ill help you",
  "Need help? with payment",
];
var textContentTime = 30000;
var ratingValue = 5;
var authToken;
var feedback;
var feedMessage;
var apiBaseEndPoint = "/HDC_Bot/";
var counter = 0;
var closetime;

/***
 * base Url
 * https://mgagement.medassistsolutions.com:443/HDC_Bot/
 * https://mgagement.medassistsolutions.com/JH/
 *
 */

//Five minutes. 60 x 5 = 300 seconds.
var maxInactivity = 50;

//The function that will be called whenever a user is active
function activity() {
  //reset the secondsSinceLastActivity variable
  //back to 0
  secondsSinceLastActivity = 0;
}

function activityWatcher() {
  if (activityValue) {
    clearTimeout(activityValue);
  }

  //Setup the setInterval method to run
  //every second. 1000 milliseconds = 1 second.
  activityValue = setTimeout(function () {
    secondsSinceLastActivity++;
    //if the user has been inactive or idle for longer
    //then the seconds specified in maxInactivity
    // console.log("activity check", secondsSinceLastActivity);

    if (secondsSinceLastActivity > maxInactivity) {
      //Redirect them to your logout.php page.
      $("#bot").fadeOut(500);

      setTimeout(function () {
        botEnglish.style.display = "none";
        logoWrap.style.display = "block";
        chatOpen = false;
      }, 700);
      // printAll();

      setTimeout(function () {
        if (!chatOpen) {
          bubbleEndHere.style.display = "block";
          $("#bubbleEndHere").fadeOut(5000);
          setTimeout(function () {
            bubbleEndGoodbye.style.display = "block";
            $("#bubbleEndGoodbye").fadeOut(3000);
            setTimeout(function () {
              logoWrap.style.display = "none";
              logoWrapDisabled.style.display = "block";
            }, 5000);
          }, 20000);
        }
      }, 10000);
    } else {
      activityWatcher();
    }
  }, 1000);
}
// ends

function onloadFunction() {
  var t,
    timeout = 30000;
  firstTime = 0;
  sessionStorage.setItem("feedMessage", false);
  logoWrap = document.getElementById("logoWrap");
  logoWrapDisabled = document.getElementById("onLoadChatDisableIcon");
  bubbleMessage1 = document.getElementById("bubbleMessage1");
  chatcontainer = document.getElementById("chatcontainer");
  botEnglish = document.getElementById("bot");
  botSpanish = document.getElementById("botSpanish");
  bubbleEndMessage = document.getElementById("bubbleEndMessage");
  bubbleEndHere = document.getElementById("bubbleEndHere");
  bubbleEndGoodbye = document.getElementById("bubbleEndGoodbye");
  successBox = document.getElementById("success-box");
  successkey = document.querySelector(".success-key");

  // star Modal

  // Get the modal
  modal = document.getElementById("starModal");

  // Get the <span> element that closes the modal
  starClose = document.getElementById("starClose");
  feedSubmit = document.getElementById("feedSubmit");
  feedbackContent = document.getElementById("feedbackContent");

  // star modal ends

  logoWrap.style.display = "block";
  logoWrapDisabled.style.display = "none";
  botEnglish.style.display = "none";
  botSpanish.style.display = "none";
  bubbleMessage1.style.display = "none";
  bubbleEndHere.style.display = "none";
  bubbleEndGoodbye.style.display = "none";
  successkey.style.display = "none";

  var activityEvents = [
    "mousedown",
    "mousemove",
    "keydown",
    "scroll",
    "touchstart",
  ];

  // if(sessionStorage.getItem("feedMessage")){
  //   feedMessage = sessionStorage.getItem("feedMessage");

  // }else{
  //   sessionStorage.setItem("feedMessage", false);
  // }

  //add these events to the document.
  //register the activity function as the listener parameter.
  activityEvents.forEach(function (eventName) {
    document.addEventListener(eventName, activity);
  });

  //   open chatbox after 10 sec
  // setTimeout(function () {
  //   englishLanguage(combined_value);
  // }, 10000);

  // function resetTimer() {
  //   if (t) {
  //     window.clearTimeout(t);
  //   }
  //   t = window.setTimeout(logout, timeout);

  function random() {
    // console.log(chatOpen);
    closetime = setInterval(function () {
      if (!chatOpen) {
        counter = (counter + 1) % textContents.length;
        // var radom = Math.floor(Math.random()*4);
        bubbleMessage1.textContent = textContents[counter];
        bubbleMessage1.style.display = "block";
        setTimeout(() => {
          bubbleMessage1.style.display = "none";
        }, 5000);
        // console.log(textContents[counter]);
      } else {
        counter = 0;
        clearInterval(closetime);
      }
    }, textContentTime);
  }
  random();
  authGenF();

  document.getElementById("starClose").addEventListener("click", function () {
    feedbackContent.value = "";
    // resetting the star value
    $(".star.selected").removeClass("selected");
    modal.style.display = "none";
  });

  function logout() {
    if (firstTime == 0) {
      logoWrap.style.display = "block";
      logoWrapDisabled.style.display = "block";
      botEnglish.style.display = "none";
      botSpanish.style.display = "none";
      firstTime++;
    }
  }
    englishLanguage(combined_value);
  // resetTimer();
  //And bind the events to call `resetTimer()`
  // ["click", "mousemove", "keypress"].forEach(function (name) {
  //     //  console.log(name);
  //     document.getElementById("logoWrap").addEventListener(name, resetTimer);

  // });
}

// close of onload

function openChatWindow() {
  firstTime = 1;
  logoWrap.style.display = "block";
  logoWrapDisabled.style.display = "none";
  botEnglish.style.display = "none";
  botSpanish.style.display = "none";
  // activityWatcsher();
}

function turn_Off_On_Sound() {
  console.log("clciked mute");
  window.speechSynthesis.cancel();
  window.SpeechSynthesisUtterance.volume = 0;
  //window.speechSynthesisInstance.pause()
}

function turn_On_Sound() {
  console.log("clciked un mute");
  window.SpeechSynthesisUtterance.volume = 10;
}

$(document).ready(function () {
  //  default make 5 star
  var onStar;

  // $("#stars li.star").addClass("selected");

  /* 1. Visualizing things on Hover - See next part for action on click */

  $("#stars li")
    .on("mouseover", function () {
      onStar = parseInt($(this).data("value"), 10); // The star currently mouse on

      // Now highlight all the stars that's not after the current hovered star
      $(this)
        .parent()
        .children("li.star")
        .each(function (e) {
          if (e < onStar) {
            $(this).addClass("hover");
          } else {
            $(this).removeClass("hover");
          }
        });
    })
    .on("mouseout", function () {
      $(this)
        .parent()
        .children("li.star")
        .each(function (e) {
          $(this).removeClass("hover");
        });
    });

  /* 2. Action to perform on click */
  $("#stars li").on("click", function () {
    var onStar;
    // ratingValue = 5;
    onStar = parseInt($(this).data("value"), 10); // The star currently selected
    var stars = $(this).parent().children("li.star");

    for (i = 0; i < stars.length; i++) {
      $(stars[i]).removeClass("selected");
    }

    for (i = 0; i < onStar; i++) {
      $(stars[i]).addClass("selected");
    }

    // JUST RESPONSE (Not needed)
    ratingValue = parseInt($("#stars li.selected").last().data("value"), 10);
    var msg = "";
    if (ratingValue > 1) {
      msg = "Thanks! You rated this " + ratingValue + " stars.";
    } else {
      msg =
        "We will improve ourselves. You rated this " + ratingValue + " stars.";
    }
  });
});

function responseMessage(msg) {
  $(".success-box").fadeIn(200);
  $(".success-box div.text-message").html("<span>" + msg + "</span>");
  successkey.style.display = "block";
}

function closeChatWindow() {
  feedMessage = sessionStorage.getItem("feedMessage");
  // let feedMessage = sessionStorage.getItem("feedMessage");
  if (firstTime == 1 && feedMessage == "false") {
    // if (firstTime == 1) {
    setTimeout(function () {
      botEnglish.style.display = "none";
      logoWrap.style.display = "block";
      logoWrapDisabled.style.display = "none";
      chatOpen = true;
      setTimeout(function () {
        modal.style.display = "block";
      }, 500);
    }, 1000);
  } else {
    setTimeout(function () {
      botEnglish.style.display = "none";
      logoWrap.style.display = "block";
      logoWrapDisabled.style.display = "none";
      chatOpen = true;
    }, 1000);
  }
}

// rating api call

function postRate(type, url) {
  try {
    authGen = localStorage.getItem("rateToken");
    dataList = {
      debtorNumber: cubrefnum,
      PageName: type,
      RatingValue: ratingValue,
      Comments: feedback,
    };
    var inputJson = JSON.stringify(dataList);
    var settings = {
      async: true,
      crossDomain: true,
      url: apiBaseEndPoint + "api/Bot/InsertRatingAndComment",
      method: "POST",
      headers: {
        authorization: "Bearer " + authGen,
        "content-type": "application/json",
        "cache-control": "no-cache",
        "Access-Control-Allow-Origin": "*",
      },
      processData: false,
      data: inputJson,
    };

    $.ajax(settings)
      .done(function (response) {
        responseMessage(response);
        var elementEl = document.getElementById("feedSubmit");
        elementEl.classList.add("success-submit");
        setTimeout(function () {
          modal.style.display = "none";
          feedbackContent.value = "";
        }, 500);
        window.open("https://mgagement.medassistsolutions.com/JH/","_blank"); // = "https://mgagement.medassistsolutions.com/JH/";
        sessionStorage.setItem("feedMessage", true);
        if (url) {
          window.open(url, "_self");
        }
      })
      .fail(function (response) {
        if (url) {
          window.open(url, "_self");
          
        }
        // window.open("https://mgagement.medassistsolutions.com/JH/","_blank");
      });
  } catch (err) {
    console.log(err);
  }
}

function authGenF(callback) {
  try {
    var settings = {
      async: true,
      crossDomain: true,
      url: apiBaseEndPoint + "token",
      method: "POST",
      headers: {
        "cache-control": "no-cache",
        accept: "text/plain",
        "Access-Control-Allow-Origin": "*",
      },
      data: "grant_type=password&username=HDC&password=ileverage",
    };

    $.ajax(settings).done(function (response) {
      authGen = response.access_token;
      localStorage.setItem("rateToken", response.access_token);
    });
  } catch (err) {
    console.log(err);
  }
}

document.getElementById("feedSubmit").addEventListener("click", function () {
  feedback = feedbackContent.value;
  postRate("close");

  // resetting the star value
  // $('.star.selected').removeClass('selected');
});

var cubrefnum = "100322";
var gid = "a7cc79d4-f636-4f97-a13f-dc7e372c1eb1";
var tid = "ED7AD2F9-BC30-47FA-8649-11A1B6D2316C";
var bot_name = "Jackson Hospital";
var combined_value = cubrefnum + "&" + gid + "&" + tid + "&" + bot_name;

document.getElementById("logoWrap").addEventListener(
  "click",
  function () {
    englishLanguage(combined_value);
  },
  false
);
document.getElementById("bubbleMessage1").addEventListener(
  "click",
  function () {
    englishLanguage(combined_value);
  },
  false
);

function englishLanguage(message) {
  function guid() {
    return (
      s4() +
      s4() +
      "-" +
      s4() +
      "-" +
      s4() +
      "-" +
      s4() +
      "-" +
      s4() +
      s4() +
      s4()
    );
  }

  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  var userId = guid().toUpperCase();
  var userName = "You";

    var secret = "EdYNsprYLYA.NeEitv3t09daqNQECqX_Y7Q1QZwqPNj3JsnZd29Ethc";

    //var secret = 'Fm_yoRZi9_M.ryF_tQoD1b1gP5wQYmSjblvXxaWcv8KDc3fQMZAFhhk';
  var user = {
    id: userId,
    name: userName,
  };
  var bot = {
    id: "Demo-WebAppBot",
    name: " Demo ChatBot",
  };
  var botConnection = new BotChat.DirectLine({
    secret: secret,
    webSocket: true,
  });
  // check bot connection

  //  console.log(botConnection);
  //   const speechOptions = {
  //     speechRecognizer: new BotChat.Speech.BrowserSpeechRecognizer(),
  //     speechSynthesizer: new BotChat.Speech.BrowserSpeechSynthesizer()
  //   };
  const speechOptions = {
    speechRecognizer: new CognitiveServices.SpeechRecognizer({
      subscriptionKey: "d7e8194024f8476e8537cf8fa54f5d09",
    }),
    speechSynthesizer: new BotChat.Speech.BrowserSpeechSynthesizer(),
    // speechSynthesizer: window.speechSynthesis.getVoices()[1],
  };
  BotChat.App(
    {
      botConnection: botConnection,
      user: user,
      bot: bot,
      locale: "en-US",
      resize: "detect",
      speechOptions: speechOptions,
    },
    document.getElementById("bot")
  );
  document.querySelector("#bot .wc-header").innerHTML =
    '<span>Jackie</span><span class="dot"></span><span id="" class="icon-close closeChatWindow"></span><span  class="myBtn chatIConNew icon-volume--down"></span><span  class="myBtn chatIConMute icon-volume--mute"></span> ';

  //botConnection.postActivity({ type: "event", from: user, name: "firstMessage", value: "100281" }).subscribe(id => console.log(""));
  // console.log("concat string:", message);

  //botConnection.postActivity({ type: "event", from: user, name: "firstMessage", value: "100281&a7cc79d4-f636-4f97-a13f-dc7e372c1eb1&ED7AD2F9-BC30-47FA-8649-11A1B6D2316C" }).subscribe(id => console.log(""));

  botConnection
    .postActivity({
      type: "event",
      from: user,
      name: "firstMessage",
      value: message,
    })
    .subscribe((id) => console.log(""));

  //botConnection.postActivity({ type: "event", from: user, name: "firstMessage", value: cubrefnum+'&'+gid+'&'+tid }).subscribe(id => console.log(""));

  window.addEventListener("beforeunload", (event) => {
    //event.returnValue = `Are you sure you want to leave?`;
    botConnection
      .postActivity({
        type: "endConversation",
        from: user,
        name: "endConversation",
        value: "endofconvo",
      })
      .subscribe((id) => console.log("Conversation ended"));
  });
  //
  $(".chatIConNew").click(function () {
    turn_Off_On_Sound();
  });
  $(".chatIConMute").click(function () {
    turn_On_Sound();
  });
  $(".closeChatWindow").click(function () {
    closeChatWindow();
  });
document.getElementsByClassName('wc-shellinput')[0].setAttribute('disabled', 'disabled');
  logoWrap.style.display = "none";
  logoWrapDisabled.style.display = "none";
  setTimeout(() => {
    botEnglish.style.display = "block";
  }, 1000);
  setTimeout(() => {
    document.getElementsByClassName('wc-shellinput')[0].removeAttribute('disabled');
  }, 8000);
  botSpanish.style.display = "none";
  chatOpen = true;
  activityWatcher();
  firstTime++;
}

// To open on select of spanish

// document.getElementById("selectSpanish").addEventListener("click", function () {
//     console.log("message to function", combined_value);
//     spanishLanguage(combined_value);

// }, false);

function spanishLanguage(message) {
  function guid() {
    return (
      s4() +
      s4() +
      "-" +
      s4() +
      "-" +
      s4() +
      "-" +
      s4() +
      "-" +
      s4() +
      s4() +
      s4()
    );
  }

  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  var userId = guid().toUpperCase();
  var userName = "User-" + Math.floor((1 + Math.random()) * 10000);
  var secret = "Vrn7y8hl7Zk.D4WPeg10eE2JFJdG4d1DqgP43-_VgaYJZJdLWydbsEg";
  var user = {
    id: userId,
    name: userName,
  };
  var bot = {
    id: "Demo-WebAppBot",
    name: " Demo ChatBot",
  };
  var botConnection = new BotChat.DirectLine({
    secret: secret,
    webSocket: true,
  });
  const speechOptions = {
    speechRecognizer: new CognitiveServices.SpeechRecognizer({
      subscriptionKey: "627daf72045647609c2d554510296d3b",
    }),
    speechSynthesizer: new BotChat.Speech.BrowserSpeechSynthesizer(),
  };
  BotChat.App(
    {
      botConnection: botConnection,
      user: user,
      bot: bot,
      resize: "detect",
      locale: "es-ES",
      speechOptions: speechOptions,
    },
    document.getElementById("botSpanish")
  );
  document.querySelector("#botSpanish .wc-header").innerHTML =
    '<span>Firstsource Help</span><span class="dot"></span><span id="" class="icon-close closeChatWindow"></span><span  class="myBtn chatIConNew icon-volume--down"></span><span  class="myBtn chatIConMute icon-volume--mute"></span> ';

  botConnection
    .postActivity({
      type: "event",
      from: user,
      name: "firstMessage",
      value: message,
    })
    .subscribe((id) => console.log(""));

  //botConnection.postActivity({ type: "event", from: user, name: "firstMessage", value: "100281&a7cc79d4-f636-4f97-a13f-dc7e372c1eb1&ED7AD2F9-BC30-47FA-8649-11A1B6D2316C" }).subscribe(id => console.log(""));

  window.addEventListener("beforeunload", (event) => {
    botConnection
      .postActivity({
        type: "endConversation",
        from: user,
        name: "endConversation",
        value: "endofconvo",
      })
      .subscribe((id) => console.log("Conversation ended"));
  });
  $(".chatIConNew").click(function () {
    turn_Off_On_Sound();
  });
  $(".chatIConMute").click(function () {
    turn_On_Sound();
  });
  $(".closeChatWindow").click(function () {
    closeChatWindow();
  });
  logoWrap.style.display = "none";
  logoWrapDisabled.style.display = "none";
  botEnglish.style.display = "none";
  setTimeout(() => {
    botSpanish.style.display = "block";
  }, 1000);
}
