{% extends 'base.html' %}

{% load static %}

{% load crispy_forms_tags %}

{% block base %}

<!-- MESSAGE Modal --------------------------------------------------------------------------------------------- -->
<div class="modal fade" id="sendMessageModal" tabindex="-1" aria-labelledby="sendMessageModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="sendMessageModalLabel">MESSAGE FORM</h1>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <div class="p-1">
  
                <form method="post" action="/message/" id="message_form" autocomplete="off">
                    {% csrf_token %}

                    <div class="mb-3">
                        <label for="receiver" class="form-label">Receipent</label>
                        <input type="text" class="form-control" id="receiver" name="receiver">
                    </div>

                    <div class="mb-3">
                        <label for="message" class="form-label">Message</label>
                        <textarea class="form-control" id="message" rows="3" name="message"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="sender" class="form-label">Sender</label>
                        <input type="text" class="form-control" id="sender" name="sender">
                    </div>
                      
  
                    <button type="submit" class="btn btn-primary mt-5 form-control shadowed">Send</button>
                </form>
            </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="window.location.reload()">Close</button>
        </div>
      </div>
    </div>
  </div>
  <!--MESSAGE Modal Ends --------------------------------------------------------------------------------------------------------------------->

<style>
    .aside__link {
        text-decoration: none;
        color:#212529;
    }

    .aside__link:hover {
        padding-bottom: 3px;
        border-bottom: 2px solid #212529;
      }
    table {
        font-size: 14px;
    }
    #user__activities {font-size: 12px;}
</style>
{% include 'part/navbar.html' %}
<div class="container-fluid">

        <!--MESSAGES-->
        {% for message in messages %}
        {% if message.tags == 'error' %}
            <div class="alert alert-danger alert-dismissible fade show message__alerts text-center" role="alert" >
                  <strong><span><i class="fa-solid fa-triangle-exclamation"></i></span>&nbsp;&nbsp;MESSAGE : </strong>{{ message }}
              <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        {% else %}
            <div class="alert alert-{{message.tags}} alert-dismissible fade show message__alerts text-center" role="alert">
              <strong>MESSAGE : </strong>{{ message }}
              <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        {% endif %}
      {% endfor %}
      <!--MESSAGES-->

    <div class="row">
        <div class="col-sm-12 col-lg-2 my-2 mobile__hidden">
            <div class="mx-1 my-2" style="border: 0.2px solid rgba(0, 0, 0, 0.1);border-radius: 5%;">
                <p class="p-2" style="background-color:#212529;color:white;">QUICK LINKS</p>
                <ul class="list-group list-group-flush">
                    <li class="list-group-item"><a href="/line/analysis/" class="aside__link">Line Analysis</a></li>
                    <li class="list-group-item"><a href="/sachet/analysis/" class="aside__link">Sachet Analysis</a></li>
                    <li class="list-group-item"><a href="/line/inspection/" class="aside__link">Line Inspection</a></li>
                    <li class="list-group-item"><a href="/sachet/inspection/" class="aside__link">Sachet Inspection</a></li>
                    <li class="list-group-item"><a href="/dispute/" class="aside__link">Disputes</a></li>
                    <li class="list-group-item"><a href="#" class="aside__link" data-bs-toggle="modal" data-bs-target="#sendMessageModal">Send Message</a></li>
                  </ul>
            </div>
        </div>

        <div class="col-sm-12 col-lg-7 my-2">
        {% block content %}

        {% endblock %}
        </div>

        <div class="col-sm-12 col-lg-3 my-2 mobile__hidden">
            <div class="mx-1 my-2" style="border: 0.2px solid rgba(0, 0, 0, 0.1);border-radius: 5%;">
                <p class="p-2" style="background-color:#212529;color:white;">QUICK SEARCH...</p>
                <form class="px-3 pb-3" action="/layout_date_search/", method="post">
                    {% csrf_token %}
                    <div class="mb-3">
                        <label for="exampleFormControlInput1" class="form-label">Search Date</label>
                        <input id="startDate" class="form-control" type="text" name="layout_date_search" />
                      </div>
                      <button type="submit" class="btn btn-primary form-control">Search</button>
                </form>
            </div>


            <div class="mx-1 my-3" style="border: 0.2px solid rgba(0, 0, 0, 0.1);border-radius: 5%;">
                <p class="p-2" style="background-color:#212529;color:white;">RECENT ACTIVITIES...</p>
                <div class="mb-3">
                    <ul class="list-group list-group-flush mx-1" id="user__activities"></ul>
                    <div class="text-center" id="spinner__box"><div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div></div>
                </div>
            </div>
        </div>
</div>
{% include 'part/footer.html' %}

<script>
    function bigImg(x){
        x.style.background = '#141850';
        x.style.color = 'white';
    }
    
    function normalImg(x){
        x.style.background='white';
        x.style.color = 'black';
    }
  </script>

  <script>
    $( function() {
        $('#startDate').datepicker({ dateFormat: 'yy-mm-dd' });
        $("#datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
        $(".datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
      
    } );
</script>

  <script>
    $(document).ready(function(){
      $("#myInput").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $("#myTable tr").filter(function() {
          $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
      });

      $("textarea").attr('rows', "3");
      capLabels();
      setActivities();
      getSetMessage();
    });
    </script>

    <script>
        function setSelect(name, data_list, add_event){
            var data = data_list.split(',,')
            var ele = document.querySelector(`#div_id_${name}`);
            var row = `<label for="${name}" class="form-label requiredField">${name}<span class="asteriskField">*</span></label>`;
            row += `<select name="${name}" class="select form-select" required="" id="id_${name}" ${add_event ? onchange = add_event : '' }"><option value="" selected="">---------</option>`;
            for(let i=0;i<data.length;i++){
                row += `<option value="${data[i]}">${data[i]}</option>`;
            }
            row += '</select>';
            ele.innerHTML = row;
        }
    </script>
    <script>
        function capLabels(){
            var lab = $('label');
            for(let i=0;i<lab.length;i++){
                lab[i].innerText = lab[i].innerText.toLocaleUpperCase();
            }
        }
    </script>

    <script>
        function setActivities(){
            var user__activities = document.getElementById('user__activities');
            $.get('/utils/recent_activities_api/', function(data, status){

                
                if (status === 'success'){
                    var row = ''
                    for(let i =0;i<data.length;i++){
                        if(data[i].description !== ''){
                        row += `<li class="list-group-item"><a href="${data[i].link}" class="nav-link aside__link">${data[i].description} | ${data[i].datetime_created}</a></li>`
                        }
                    }
                    user__activities.innerHTML = row;
                    $('#spinner__box').hide();
                }
            })
        }
    </script>

    <script>
        function autocomplete(inp, arr) {
          /*the autocomplete function takes two arguments,
          the text field element and an array of possible autocompleted values:*/
          var currentFocus;
          /*execute a function when someone writes in the text field:*/
          inp.addEventListener("input", function(e) {
              var a, b, i, val = this.value;
              /*close any already open lists of autocompleted values*/
              closeAllLists();
              if (!val) { return false;}
              currentFocus = -1;
              /*create a DIV element that will contain the items (values):*/
              a = document.createElement("DIV");
              a.setAttribute("id", this.id + "autocomplete-list");
              a.setAttribute("class", "autocomplete-items");
              /*append the DIV element as a child of the autocomplete container:*/
              this.parentNode.appendChild(a);
              /*for each item in the array...*/
              for (i = 0; i < arr.length; i++) {
                /*check if the item starts with the same letters as the text field value:*/
                if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
                  /*create a DIV element for each matching element:*/
                  b = document.createElement("DIV");
                  /*make the matching letters bold:*/
                  b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
                  b.innerHTML += arr[i].substr(val.length);
                  /*insert a input field that will hold the current array item's value:*/
                  b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
                  /*execute a function when someone clicks on the item value (DIV element):*/
                  b.addEventListener("click", function(e) {
                      /*insert the value for the autocomplete text field:*/
                      inp.value = this.getElementsByTagName("input")[0].value;
                      /*close the list of autocompleted values,
                      (or any other open lists of autocompleted values:*/
                      closeAllLists();
                  });
                  a.appendChild(b);
                }
              }
          });
          /*execute a function presses a key on the keyboard:*/
          inp.addEventListener("keydown", function(e) {
              var x = document.getElementById(this.id + "autocomplete-list");
              if (x) x = x.getElementsByTagName("div");
              if (e.keyCode == 40) {
                /*If the arrow DOWN key is pressed,
                increase the currentFocus variable:*/
                currentFocus++;
                /*and and make the current item more visible:*/
                addActive(x);
              } else if (e.keyCode == 38) { //up
                /*If the arrow UP key is pressed,
                decrease the currentFocus variable:*/
                currentFocus--;
                /*and and make the current item more visible:*/
                addActive(x);
              } else if (e.keyCode == 13) {
                /*If the ENTER key is pressed, prevent the form from being submitted,*/
                e.preventDefault();
                if (currentFocus > -1) {
                  /*and simulate a click on the "active" item:*/
                  if (x) x[currentFocus].click();
                }
              }
          });
          function addActive(x) {
            /*a function to classify an item as "active":*/
            if (!x) return false;
            /*start by removing the "active" class on all items:*/
            removeActive(x);
            if (currentFocus >= x.length) currentFocus = 0;
            if (currentFocus < 0) currentFocus = (x.length - 1);
            /*add class "autocomplete-active":*/
            x[currentFocus].classList.add("autocomplete-active");
          }
          function removeActive(x) {
            /*a function to remove the "active" class from all autocomplete items:*/
            for (var i = 0; i < x.length; i++) {
              x[i].classList.remove("autocomplete-active");
            }
          }
          function closeAllLists(elmnt) {
            /*close all autocomplete lists in the document,
            except the one passed as an argument:*/
            var x = document.getElementsByClassName("autocomplete-items");
            for (var i = 0; i < x.length; i++) {
              if (elmnt != x[i] && elmnt != inp) {
                x[i].parentNode.removeChild(x[i]);
              }
            }
          }
          /*execute a function when someone clicks in the document:*/
          document.addEventListener("click", function (e) {
              closeAllLists(e.target);
          });
        }
        
        /*An array containing all the country names in the world:*/
        
        $.get('/api/v1/user/users_api/', function(data, status){
            console.log(status)
            if(status === 'success'){
                autocomplete(document.getElementById("receiver"), data);
            }
        })
        /*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
        //autocomplete(document.getElementById("receiver"), countries);
    </script>

    <script>
        $("#message_form").submit(async function( event ) {
            event.preventDefault();
            var receiver = $("#receiver").val();
            var message = $("#message").val();
            var sender = $("#sender").val();
            var currentUrl = window.location.href;

            var res = await fetch('/api/v1/user/message/', {method: 'POST', body: JSON.stringify({receiver: receiver, message:message, sender:sender}) });
            var data = await res.json()

            if (res.ok){
                $('#sendMessageModal').modal('hide');
                if (data.error)alert(data.error)
                if (data.message)alert(data.message)
            }

            $("#receiver").val('');
            $("#message").val('');
            $("#sender").val('');
          });
    </script>

    <script>
        async function getSetMessage(){
            var chat_box_count = document.querySelector('#chat_box_count');
            var res = await fetch('/api/v1/user/get_user_message_api/');
            var data = await res.json()

            if (res.ok){
                if (data.message.length > 0){
                    chat_box_count.innerHTML = `nbsp;<i class="bi bi-${data.message.length}-square" style="color: white;" onclick="window.location.href='/message'"></i>`
                }
            }
        }
    </script>
    

{% endblock %}