var ticketId;
var clickedTicketID;
var url = '/test';

//--> just for test
var ticketStatus = 'open';
//<--



//Get tickets list from server
function getTicketsList() {
  $.ajax({
    url: url + "?currentUser=" + '#####',
    beforeSend: function (e) {
      //Loader
      loaderHandler('show')
    },
    error: function () {
      //error alert
      loaderHandler('hide')
      errorHandler('show', 'خطا در برقراری ارتباط !!!')
    }
  }).done(function (result) {
    //*****fill chats list******

  });

}

// Run "Get tickets list" on page load
getTicketsList();


//read tickets list and ready to open details
function readTicketsList() {
  document.querySelectorAll('.ticket-item').forEach(item => {
    item.addEventListener('click', event => {
      ticketId = item.id
      // console.log(ticketId)
      showDetails(ticketId)

      //change background of clicked ticket
      var clickedItem = document.querySelector('.clicked-ticket')
      if (clickedItem !== null) {
        clickedItem.classList.remove('clicked-ticket')
      }
      item.classList.toggle('clicked-ticket')
      ticketId = item.id

    })
  })

}
readTicketsList()

//Send clicked ticket Id to server , get the details and show 
function showDetails(clickedItemId) {

  //set clickedTicketID for other usages
  clickedTicketID = clickedItemId


    //get clicked ticket details from server
    $.ajax({
      url: url + "?ticketId=" + clickedItemId,
      beforeSend: function (e) {
        //Loader
        loaderHandler('show')
      },
      error: function () {
        //error alert
        loaderHandler('hide')
        errorHandler('show', 'خطا در برقراری ارتباط !!!')
      }
    }).done(function (result) {


    //*****fill chats list******

      //Hide new ticket area and show ticket details
      document.getElementById('new-ticket-container').classList.replace('show', 'hide')
      document.getElementById('ticket-details-container').classList.replace('hide', 'show')

      //Check just if ticket status is open, show answer editor
      if (ticketStatus == 'open') {
        document.querySelector('.answer-editor').classList.replace('hide','show')
        console.log(ticketStatus);
      }

    });

  console.log(clickedTicketID)


  //read ticket list from left side and ready to click on each item
  readTicketsList()


  // -------->

  //*****fill chats list******

  //Hide new ticket area and show ticket details
  document.getElementById('new-ticket-container').classList.replace('show', 'hide')
  document.getElementById('ticket-details-container').classList.replace('hide', 'show')

  //Check just if ticket status is open, show answer editor
  if (ticketStatus == 'open') {
    document.querySelector('.answer-editor').classList.replace('hide', 'show')
    console.log(ticketStatus);
  }

  // <--------




}




//show new ticket area
document.getElementById('new-ticket-btn').addEventListener('click', function () {

  document.getElementById('new-ticket-container').classList.replace('hide', 'show')
  document.getElementById('ticket-details-container').classList.replace('show', 'hide')

  //Scroll on new ticket editor (on mobile)
  window.scrollTo(0, document.body.scrollHeight);
})


//set sticky header with
$(document).ready(function () {

  $("#ticket-details-header").css({
    'width': ($(".ticket-details-container").width() + 'px')
  });
});


//Show and Hide Loader
function loaderHandler(toggler) {
  var loadSection = document.querySelector('.loader-wrap')
  if (toggler == 'show') {
    loadSection.classList.replace('hide', 'show');

  } else if (toggler == 'hide') {
    loadSection.classList.replace('show', 'hide');
  }
}

//Show and Hide Error box
function errorHandler(toggler, message) {
  var errorSection = document.querySelector('.error-back')
  var errorMessage = document.getElementById('error-message')
  if (toggler == 'show') {
    errorSection.classList.replace('hide', 'show');
    errorMessage.innerText = message

  } else if (toggler == 'hide') {
    errorSection.classList.replace('show', 'hide');
  }

}


//New ticket editor validation and success message
CKEDITOR.replace('new-ticket-editor');
$("#new-ticket-form").submit(function (e) {
  var messageLength = CKEDITOR.instances['new-ticket-editor'].getData().replace(/<[^>]*>/gi, '').length;
  // console.log(messageLength)
  if (!messageLength) {

    showMessage('لطفا ابتدا متن تیکت مورد نظر خود را وارد کنید', 'danger')
    e.preventDefault();

  } else {
    
    
    //remove it -->
    alert('send data to server here')
    e.preventDefault();
    //<--
    
    
    
    showMessage('تیکت شما با موفقیت ارسال شد', 'success')
    
      //get list again (from server) to set changes
      getTicketsList()

      //read ticket list from left side and ready to click on each item
      readTicketsList()
  }
});




//Answer editor validation and success message
CKEDITOR.replace('answer-editor');
$("#answer-form").submit(function (e) {
  var messageLength = CKEDITOR.instances['answer-editor'].getData().replace(/<[^>]*>/gi, '').length;
  // console.log(messageLength)
  if (!messageLength) {

    showMessage('لطفا ابتدا پاسخ مورد نظر خود را وارد کنید', 'danger')
    e.preventDefault();

  } else {
    
    
    //remove it -->
    alert('send data to server here')
    e.preventDefault();
    //<--
    
    
    
    showMessage('پاسخ شما با موفقیت ارسال شد', 'success')
    
    //get list again (from server) to set changes
    getTicketsList()
    
    //read ticket list from left side and ready to click on each item
    readTicketsList()
    
  }
});


//message 
function showMessage(message, messageType) {
  var messageContainer = document.querySelector('.message-container')
  document.querySelector('.message-container label').innerHTML = '&#9747'
  document.querySelector('.text-message').innerText = message
  messageContainer.style.display = 'block'
  // document.getElementById('#ticket-chats-container').scrollTop = 0;
  if (messageType == 'success') {
    messageContainer.style.background = '#41d941'
    console.log('success')
    document.querySelector('#send-answer').style.display = 'none'
    // document.querySelector('#answer-editor').style.display = 'none'


  } else if (messageType == 'danger') {
    messageContainer.style.background = 'red'
    console.log('danger')
  }

  //scroll up to message
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;


  //close the message box
  document.querySelector('.message-container label').addEventListener('click', function () {
    document.querySelector('.message-container').style.display = 'none';
  })
}