<!DOCTYPE html>
<!-- [START_EXCLUDE] -->
<%--
  ~ Copyright 2018 Google Inc.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License"); you
  ~ may not use this file except in compliance with the License. You may
  ~ obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  ~ implied. See the License for the specific language governing
  ~ permissions and limitations under the License.
  --%>
<!-- [END_EXCLUDE] -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.google.rbm.samples.servlets.CustomerSupportChat" %>
<%@ page import="com.google.rbm.samples.servlets.CustomerSupportMessages" %>
<html>
<head>
    <link href='//fonts.googleapis.com/css?family=Marmelad' rel='stylesheet' type='text/css'>
    <link
        rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
        crossorigin="anonymous">
    </link>
    <link rel="stylesheet" href="/stylesheets/style.css?<%= new java.util.Date().getTime() %>">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <link href="/stylesheets/emoji.css" rel="stylesheet">

    <script
      src="https://code.jquery.com/jquery-3.3.1.min.js"
      integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
      crossorigin="anonymous">
    </script>

    <script
        src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"
        integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm"
        crossorigin="anonymous">
    </script>

    <link rel="icon"
          type="image/png"
          href="/images/favicon.png">

    <title>ACME Bank Demo Customer Support</title>

    <script type="text/javascript">
        // regex for testing phone number format
        var regex = /^\+(?:[0-9] ?){6,14}[0-9]$/;

        var blinkInterval;
        var originalTitle;
        var prevNumOfMessages = 0;
        var firstRetrieval = true;

        var chatDing = new Audio("/files/chat_ding.mp3");

        $(document).ready(function() {
            originalTitle = $(document).find("title").text();

            <% if (session.getAttribute("phone_number") != null) { %>
                loadMessages();
            <% } %>

            // Initializes and creates emoji set from sprite sheet
            window.emojiPicker = new EmojiPicker({
                emojiable_selector: '[data-emojiable=true]',
                assetsPath: '/img',
                popupButtonClasses: 'fa fa-smile-o'
            });

            window.emojiPicker.discover();

            $("#send-msg-btn").click(function(e) {
                e.preventDefault();

                sendMessage();
            });

            $("#message").keypress(function(e) {
                if(e.which == 13) {
                    sendMessage();
                }
            });

            $(document).on("submit", "#message-form", function(event){
                event.preventDefault();
            });

            $(window).focus(function() {
                killInterval();
            });

            $("#start-chat-btn").click(function(e) {
                e.preventDefault();

                starChat();
            });

            // start chat form submission
            $(document).on("submit", "#conversation-form", function(event){
                event.preventDefault();

                removeErrors();

                var phoneNumber = $("#phone-number").val();

                if($.trim(phoneNumber) == "") {
                    event.stopPropagation();

                    showInputError("#phone-number", "Sorry, but you must provide a " +
                        "phone number to an RCS-enabled device.");
                }
                else if(!regex.test(phoneNumber)) {
                    event.stopPropagation();

                    showInputError("#phone-number", "Sorry, but you must enter your " +
                        "phone number in the format of +12223334444.");
                }
                else {
                    phoneNumber = encodeURIComponent(phoneNumber);
                    showWaiting("Initiating Chat...", "#start-chat-btn");

                    $.getJSON("/initChat?phone_number="+phoneNumber, function(response) {
                        resetButton("#start-chat-btn");

                        if(response.response == "ok") {
                           window.location.reload();
                        }
                        else {
                           showErrorMessage("<p>Sorry, but the chat could not be initiated. " +
                               "Make sure that you have registered your phone as a test device " +
                               "prior to initiating a chat.</p>" +
                               "<p class=\"text-center\"><a href=\"index.jsp\"" +
                               "class=\"btn btn-outline-secondary\">Register Now</a></p>",
                               "#fail-msg");
                        }
                    });
                }
            });
        });

        function sendMessage() {
            var message = $("#message").val();

            showWaiting("Sending reply...", "#send-msg-btn");

            $.getJSON("/sendMessage?message=" + message, function(data) {
                resetButton( "#send-msg-btn");

                if(data.response == "ok") {
                    $(".emoji-wysiwyg-editor").html("");

                    loadMessages();
                }
                else {
                    alert(data.message);
                }
            });
        }

        function loadMessages() {
            $.getJSON("/retrieveMessages", function(data) {
                var messageHTML = "";
                var numOfMessages = 0;

                for(var i = 0; i < data.messages.length; i++) {
                    messageHTML += '<div class="mt-2">';

                    var floatClassName = "float-right";
                    var image = "/images/silhouette.png";

                    if(data.messages[i].sender == "me") {
                        floatClassName = "float-left";
                        image = "/images/sean-headshot.png";
                    }

                    messageHTML += '<div style="width: 40px;" class="' + floatClassName + '">';
                    messageHTML += '<img src="' + image + '" width="40" />';
                    messageHTML += '</div>';
                    messageHTML += '<div class="' + floatClassName + '">';

                    if(data.messages[i].sender == "me") {
                        messageHTML += '<div class="message">' +
                                       '<div class="arrow">' +
                                        '<div class="outer"></div>' +
                                        '<div class="inner"></div>' +
                                      '</div>' +
                                      '<div class="message-body">' +
                                        data.messages[i].body +
                                      '</div>' +
                                    '</div>';
                    }
                    else {
                        messageHTML += '<div class="message">' +
                                      '<div class="message-body-right">' +
                                        data.messages[i].body +
                                      '</div>' +
                                      '<div class="arrow-right">' +
                                        '<div class="outer"></div>' +
                                        '<div class="inner"></div>' +
                                      '</div>' +
                                    '</div>';
                        numOfMessages++;
                    }

                    messageHTML += '</div>';

                    messageHTML += '<div class="clearfix"></div>';
                    messageHTML += '</div>';
                }

                // if this is the first time we loaded messaging, set an interval to do this
                // every 1,000 milliseconds
                if(firstRetrieval) {
                    setInterval(loadMessages, 1000);
                }

                firstRetrieval = false;

                $("#chat-messages").html(messageHTML);

                if(numOfMessages != prevNumOfMessages) {
                    prevNumOfMessages = numOfMessages;

                    chatDing.play();
                    blinkInterval = setInterval(newChatBlink, 1000);
                }

                scrollToBottom();
            });
        }

        function killInterval() {
            if(blinkInterval != undefined && blinkInterval != false) {
                clearInterval(blinkInterval);
                blinkInterval = false;

                $(document).find("title").text(originalTitle);
            }
        }

        function newChatBlink() {
            var title = $(document).find("title").text();
            if(title.indexOf("Customer Support") >= 0) {
                title = "New Message";
            }
            else {
                title = originalTitle;
            }

            $(document).find("title").text(title);
        }

        function scrollToBottom() {
            var chatMessages = $("#chat-messages");
            var height = chatMessages[0].scrollHeight;
            chatMessages.scrollTop(height);
        }

        function resetButton(button) {
            $(button).html($(button).data("original-text"));
        }

        function showWaiting(waitingText, button) {
            var loadingText = '<i class="fa fa-circle-o-notch fa-spin"></i> ' + waitingText;
            if ($(button).html() !== loadingText) {
                $(button).data("original-text", $(button).html());
                $(button).html(loadingText);
            }
        }

        function resetButton(button) {
            $(button).html($(button).data("original-text"));
        }

        function starChat() {
            $("#fail-msg").hide();

            $("#conversation-form").submit();
        }

        function removeErrors() {
            $("input").removeClass("is-invalid");
        }

        function showInputError(inputId, message) {
            $(inputId).addClass("is-invalid");
            $(inputId).parent().find(".invalid-feedback").html(message);
        }

        function showErrorMessage(message, failId) {
            $(failId).html(message);
            $(failId).show();
        }
    </script>
</head>
<body>
    <div class="container" style="padding-top: 20px;">
        <div class="text-center center-block"><img src="/images/acme-bank-logo.png" /></div>

        <% if (session.getAttribute("phone_number") == null) { %>
            <div class="row">
                <div class="col-xs-12 col-sm-8 offset-sm-2 col-md-6 offset-md-3">
                    <form method="get" action="/initChat" id="conversation-form">
                        <h4 class="text-center">Enter your registered test device phone number:</h4>
                        <input class="form-control" id="phone-number" required autofocus
                            type="text" name="phone_number" placeholder="+12223334444" value="" />

                        <div class="invalid-feedback"></div>
                        <a
                            id="start-chat-btn"
                            class="btn btn-lg btn-primary btn-block" href="#">Start Chart</a>
                    </form>

                    <div class="alert alert-danger text-center" style="display: none;"
                        id="fail-msg" role="alert">
                        Sorry, but chat could not be initiated. Make sure that you have
                        registered your phone as a test device prior to initiating the chat.
                    </div>
                </div>
            </div>
        <% } else {%>
            <div class="row" style="margin-top: 20px;">
                <div class="col-sm-8 offset-sm-2 text-center">
                    <p>You are now chatting with <%= session.getAttribute("phone_number") %>.</p>
                    <p>
                        <a href="/chatReset?phone_number=<%= session.getAttribute("phone_number").toString().replace("+", "%2B") %>">
                            Click here to reset the ACME Bank Demo
                        </a>
                    </p>
                </div>
                <div id="chat-messages" class="col-xs-12 col-sm-8 offset-sm-2 col-md-6 offset-md-3"
                     style="background: #fff; padding: 10px; height: 300px; overflow-y: auto; overflow-x: hidden; border: 1px solid #ccc;">

                </div>
                <div class="col-xs-12 col-sm-8 offset-sm-2 col-md-6 offset-md-3" style="margin-top: 5px; padding: 0px;">
                    <form method="get" action="/sendMessage" id="message-form">
                        <p class="lead emoji-picker-container">
                            <textarea id="message" class="form-control textarea-control" rows="3"
                                placeholder="Write response to user" data-emojiable="true" data-emoji-input="unicode"></textarea>
                        </p>

                        <div id="buttons" class="mt-2">
                          <div class="float-right">
                            <a href="#" class="btn btn-primary" id="send-msg-btn">Send</a>
                          </div>
                          <div class="clearfix"></div>
                        </div>
                    </form>
                </div>
            </div>
        <% } %>
    </div>
</body>

<script src="/javascripts/config.js"></script>
<script src="/javascripts/util.js"></script>
<script src="/javascripts/jquery.emojiarea.js"></script>
<script src="/javascripts/emoji-picker.js"></script>
</html>
