checkRoute();
let card;

let userBasics = JSON.parse(localStorage.getItem('user_profile')) || [];


  //userBasics = JSON.parse(userBasics);
if(userBasics !== [] && typeof(userBasics) !== 'string'){
  $('.userName').html(`<h2 class="user-name text-white mt-lg-3 mt-xl-1 fw-bold">Hi ${userBasics.user_info.userName}</h2>`);
}

function checkRoute() {
  let jwt_token = get_jwt_token();
  if(jwt_token == undefined) {
    window.location.replace("login.html");
  }
  axios({
    method: 'post',
    url: 'https://www.choozmo.com:8887/user_profile',
    headers: { 
        'accept': 'text/html',
        'Authorization': `Bearer ${jwt_token}`
     }
  }).then(res => {
    console.log(res.data);
    // if(res.status !== 200) {
    //   window.location.replace("login.html");
    // }
    var userName='';
    userName+=' <h2 class="user-name text-white mt-lg-3 mt-xl-1 fw-bold">Hi '+res.data.user_info.userName+'</h2>';
    $('.userName').html(userName);
  }).catch(err => {
    console.log(err);
    window.location.replace("login.html");
  });
}

let lan = localStorage.getItem('lan');

$('.dropdown-toggle').click(() => {
  lan = localStorage.getItem('lan');
  checkLan();
});

checkLan();

function checkLan() {
  if(lan == 'en') {
    $('.btn-makev').css('display', 'none');
    $('.btn-makelong').css('display', 'none');
  } else {
    $('.btn-makev').css('display', 'block');
    $('.btn-makelong').css('display', 'block');
    $('#slide_raw_url').attr('placeholder', 'SLIDE連結（連結須為公開）')
  }
}

const btnLoginPage = document.querySelector('.btn-login');
const btnUserProfile = document.querySelector('.btn-userProfile');
const btnLogout = document.querySelector('.btn-logout');
function loginControl() {
  btnLoginPage.style.display = 'none';
  btnLogout.style.display = 'block';
  btnUserProfile.style.display = 'block';
}

loginControl();

JsLoadingOverlay.show({
  "overlayBackgroundColor": "#FFFFFF",
  "overlayOpacity": "1",
  "spinnerIcon": "ball-circus",
  "spinnerColor": "#B9DDF3",
  "spinnerSize": "1x",
  "overlayIDName": "overlay",
  "spinnerIDName": "spinner",
  "offsetX": 0,
  "offsetY": 0,
  "containerID": "avatar-cards",
  "lockScroll": false,
  "overlayZIndex": 9998,
  "spinnerZIndex": 9999
});

window.setTimeout(() => {
  JsLoadingOverlay.hide()
}, 5000)


function getAvatar() {
  let jwt_token = get_jwt_token();
  if(jwt_token == undefined) {
    window.location.replace("login.html");
  }
  axios({
    method: 'post',
    url: 'https://www.choozmo.com:8887/get_avatar_by_role',
    headers: { 
        'accept': 'text/html',
        'Authorization': `Bearer ${jwt_token}`
     }
  }).then(res => {
    console.log(res.data);
    let result = [...res.data];
    let str = '';
    let carStr = '';
    for(let i = 0; i < result.length; i++) {
      str += `<option value="${result[i].num}">${result[i].name}</option>`
    }
    for(let i = 0; i < result.length; i++) {
      carStr += `<div class="card item col" data-avatar="${result[i].name}" data-img="${result[i].name.toLowerCase()}">
                    <div class="imgfr"><img src="static/img/${result[i].name.toLowerCase()}.webp" class="card-img-top" alt="..."></div>
                    <div class="card-body">
                        <h5 class="card-title">${result[i].name.toLowerCase()}</h5>
                    </div>
                </div>`;
    }
    $('#avatar').html(`<option value="Choose Character" selected="selected" disabled>Choose Character</option>${str}`);
    $('.avatar-cards').html(carStr);
    if(lan = 'en') {
      $('#avatar option:disabled').val('請選擇人物')
      $('#avatar option:disabled').text('請選擇人物')
    }
    card = document.getElementsByClassName('card');
    console.log(card);
    addCardListener(card);
    avatarChange()
  }).catch(err => {
    console.log(err);
  });
}

getAvatar();


var client_id = Date.now();
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
});
var myModal = new bootstrap.Modal(document.getElementById('history'), {
  keyboard: false
})
var avatarModal = new bootstrap.Modal(document.getElementById('avatarmega'), {
  keyboard: false
})
var modalImg = document.querySelector("#avatarmega .modal-img");
var modalTitle = document.querySelector("#avatarmega .modal-title");
var avatarSelector = document.getElementById("avatar");
// var card = document.getElementsByClassName('card');
// card = [...card];
avatarSelector.addEventListener('change', avatarChange);
// avatarChange();

function addCardListener(card) {
  for (let i = 0; i < card.length; i++) {
    card[i].addEventListener('click', openavatarModel);
  }
}

// addCardListener();

function avatarChange() {
  var value = avatarSelector.options[avatarSelector.selectedIndex].text;
  for (let i = 0; i < card.length; i++) {
    card[i].classList.remove('active');
    if (card[i].dataset.avatar == value) {
      card[i].classList.add('active');
    }
  }
}

function openavatarModel() {
  console.log(this.dataset.img);
  modalImg.setAttribute("src", `static/img/${this.dataset.img}.webp`);
  modalTitle.textContent = `${this.dataset.avatar}`;
  avatarModal.show();
}

$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event) {
  files = event.target.files;
  var data = new FormData();
  //data.append('file', $('.img_up1').prop('files')[0]);
  data.append('file', files[0]);
  // append other variables to data if you want: data.append('field_name_x', field_value_x);
  $(this).next().text('');
  $(this).next().html('<img src="static/img/Spinner-1s-181px.gif">');
  $.ajax({
    type: 'POST',
    processData: false, // important
    contentType: false, // important
    data: data,
    url: 'https://www.choozmo.com:8887/uploadfile',
    dataType: 'json',
    success: function (jsonData) {
      event.target.previousSibling.value = jsonData.msg;
      $(this).prev().val(jsonData.msg);
      event.target.nextSibling.innerHTML = '';
      event.target.nextSibling.textContent = '上傳檔案';
      //console.log($(this).next());
      //$(this).next().html('上傳檔案');
      //$(this).next().text('上傳檔案');
    },
    error: function (error) {
      event.target.nextSibling.innerHTML = '';
      event.target.nextSibling.textContent = '上傳檔案';
      alert('圖片錯誤');
    }
  });
}

const slide_button = document.querySelector('#send_slide');
$("#send_slide").click(function () {
  slide_button.setAttribute('disabled', '');
  setTimeout(function () {
    slide_button.removeAttribute('disabled')
  }, 15000);
  avatar = $('.avatar').val();
  var step;
  multiLang = 0
  if ($('#multiLang').prop("checked")) {multiLang = 1;}
  dataOBJ = {'slide_url':$('#slide_raw_url').val(),"avatar": avatar,"multiLang":multiLang, "client_id": client_id }
  objstr = JSON.stringify(dataOBJ);
  jwt_token =  get_jwt_token()
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "https://www.choozmo.com:8887/make_anchor_video_gSlide");
  xhr.setRequestHeader("accept", "application/json");
  xhr.setRequestHeader("Authorization","Bearer "+jwt_token);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      Swal.fire({
        title: "資料已送出",
        icon: 'success',
        text: '資料已傳送，請耐心等候',
        confirmButtonColor: '#3085d6',
      });
    }
  };
  var data = renderXHR_data(dataOBJ)
  console.log(data)
  result = xhr.send(objstr);
});

var loaded_data = ''
function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
  document.querySelector('.loader').style.display = "block";
  let jwt_token = get_jwt_token();
  axios({
    method: 'post',
    url: 'https://www.choozmo.com:8887/history_input',
    headers: { 
        'accept': 'application/json',
        'Authorization': `Bearer ${jwt_token}`
     }
  }).then(res => {
    console.log(res.data);
    loaded_data = res.data;
    var historyList = document.querySelector('.historyList');
    historyList.innerHTML = '';
    for (var obj of loaded_data) {
      var list = document.createElement('li');
      list.id = obj.id;
      // div-imgfr
      var divImgfr = document.createElement('div');
      divImgfr.classList.add('item_imgfr');
      var img = document.createElement('img');
      img.setAttribute('src', obj['image_urls'][0]);
      divImgfr.appendChild(img);
      // div-content
      var contentBox = document.createElement('div');
      contentBox.classList.add('content-box');
      var boxTitle = document.createElement('p');
      boxTitle.classList.add('box-title');
      boxTitle.textContent = obj.name;
      boxTitle.id = obj.id;
      boxTitle.setAttribute('onclick', `direct(${obj.id})`);

      var boxLink = document.createElement('span');
      boxLink.classList.add('box-link');
      boxLink.setAttribute("data-url", obj.link);
      boxLink.setAttribute('onclick', 'view()');
      boxLink.innerHTML = '<i class="fas fa-play-circle me-1"></i>觀看影片';
      contentBox.appendChild(boxTitle);
      contentBox.appendChild(boxLink);
      list.classList.add("historyList-item");
      list.appendChild(divImgfr);
      list.appendChild(contentBox);
      historyList.appendChild(list);
    }
    document.querySelector('.loader').style.display = "none";
  
  }).catch(err => {
    console.log(err);
  });
}

function direct(id) {
  location.href = `make_video2.html?id=${id}`;
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "250px";
}

function view() {
  event.stopPropagation();
  console.log(event.target);
  if (event.target.nodeName === 'I') {
    return;
  } else {
    window.open(`http://${event.target.dataset.url}`, '_blank');
  }
}

function renderXHR_data(jsonObj) {
  XHRstring = ''
  for (const [key, value] of Object.entries(jsonObj)) {
    console.log(value)
    if (typeof (value) == "object") {
      XHRstring += (key+'=['+value.join(',')+']&')
    }
    else {
      XHRstring += (key + '=' + value + '&')
    }
  }
  XHRstring = XHRstring.substring(0, XHRstring.length - 1);
  return XHRstring
}

function get_jwt_token(){
  jwt_raw = document.cookie.split(';').filter(s=>s.includes('jwt_token'))[0];
  if(!jwt_raw) {return}
  return jwt_raw.split('=')[1];
}

 getpathId();

function getpathId() {
  id = window.location.search.split('?').pop();
  return id.split('=')[1];
  //load_data(id);
}
getData();

function getData() {
  let jwt_token = get_jwt_token();
  axios({
    method: 'post',
    url: 'https://www.choozmo.com:8887/history_input',
    headers: { 
        'accept': 'application/json',
        'Authorization': `Bearer ${jwt_token}`
     }
  }).then(res => {
    loaded_data = res.data;
    console.log(loaded_data);
    const id = getpathId();
    load_data(id, loaded_data);
  }).catch(err => {
    console.log(err);
  });
} 


