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() {
  for (let i = 0; i < card.length; i++) {
    card[i].addEventListener('click', openavatarModel);
  }
}

addCardListener();

function avatarChange() {
  var value = avatarSelector.options[avatarSelector.selectedIndex].text;
  $('.owl-carousel').trigger('to.owl.carousel', avatarSelector.selectedIndex);
  console.log(value);
  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: '/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 button = document.querySelector('.next');

$(".next").click(function () {
  button.setAttribute('disabled', '');
  setTimeout(function () {
    button.removeAttribute('disabled')
  }, 4000);
  avatar = $('.avatar').val();
  name_title = $('.title_new').val();
  txtARR = [];
  imgARR = [];
  var step;
  let contentIdx = document.querySelectorAll(".txtsrc").length;
  for (let i = 1; i < (contentIdx + 1); i++) {
    if ($(`.txtsrc${i}`).val() != "") {
      txtARR.push($(`.txtsrc${i}`).val())
    }
  }
  let imgIdx = document.querySelectorAll(".imgsrc").length;
  for (let i = 1; i < (imgIdx + 1); i++) {
    if ($(`.imgsrc${i}`).val() != "") {
      imgARR.push($(`.imgsrc${i}`).val())
    }
  }
  multiLang = 0
  if ($('#multiLang').prop("checked")) {multiLang = 1;}
  dataOBJ = { "name": name_title, "text_content": txtARR, "image_urls": imgARR, "avatar": avatar,"multiLang":multiLang, "client_id": client_id }
  objstr = JSON.stringify(dataOBJ);
  console.log(dataOBJ)
  jwt_token =  get_jwt_token()
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/make_anchor_video");
  xhr.setRequestHeader("accept", "application/json");
  xhr.setRequestHeader("Authorization","Bearer "+jwt_token)
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      responseOBJ = JSON.parse(xhr.responseText)
      if (responseOBJ.msg=='ok')
      {
        Swal.fire({
          title: "資料已送出",
          icon: 'success',
          text: '資料已傳送，請耐心等候',
          confirmButtonColor: '#3085d6',
        });
      }
      else{
        Swal.fire({
          title: "發生錯誤",
          icon: 'error',
          text: responseOBJ.msg,
          confirmButtonColor: '#3085d6',
        });
      }
      
    }
  };
  var data = renderXHR_data(dataOBJ)
  console.log(data)
  result = xhr.send(objstr);
});
const buttonSend = document.querySelector('#sendBTN');
$("#sendBTN").click(function () {
  buttonSend.setAttribute('disabled', '');
  setTimeout(function () {
    buttonSend.removeAttribute('disabled')
  }, 4000);
  avatar = $('.avatar').val();
  name_title = $('.title_new').val();
  txtARR = [];
  imgARR = [];
  var step;
  let contentIdx = document.querySelectorAll(".txtsrc").length;
  for (let i = 1; i < (contentIdx + 1); i++) {
    if ($(`.txtsrc${i}`).val() != "") {
      txtARR.push($(`.txtsrc${i}`).val())
    }
  }
  let imgIdx = document.querySelectorAll(".imgsrc").length;
  for (let i = 1; i < (imgIdx + 1); i++) {
    if ($(`.imgsrc${i}`).val() != "") {
      imgARR.push($(`.imgsrc${i}`).val())
    }
  }
  multiLang = 0
  if ($('#multiLang').prop("checked")) {multiLang = 1;}
  dataOBJ = { "name": name_title, "text_content": txtARR, "image_urls": imgARR, "avatar": avatar,"multiLang":multiLang, "client_id": client_id }
  objstr = JSON.stringify(dataOBJ);
  console.log(dataOBJ)
  jwt_token =  get_jwt_token()
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/make_anchor_video_long");
  xhr.setRequestHeader("accept", "application/json");
  xhr.setRequestHeader("Authorization","Bearer "+jwt_token)
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      responseOBJ = JSON.parse(xhr.responseText)
      if (responseOBJ.msg=='ok')
      {
        Swal.fire({
          title: "資料已送出",
          icon: 'success',
          text: '資料已傳送，請耐心等候',
          confirmButtonColor: '#3085d6',
        });
      }
      else{
        Swal.fire({
          title: "發生錯誤",
          icon: 'error',
          text: responseOBJ.msg,
          confirmButtonColor: '#3085d6',
        });
      }
      
    }
  };
  var data = renderXHR_data(dataOBJ)
  console.log(data)
  result = xhr.send(objstr);
});

const slide_button = document.querySelector('#send_slide');
$("#send_slide").click(function () {
  slide_button.setAttribute('disabled', '');
  setTimeout(function () {
    slide_button.removeAttribute('disabled')
  }, 4000);
  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", "/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);
});

$(".gen_avatar").click(function () {
  dataOBJ = { "imgurl": $('.img_src').val() }
  objstr = JSON.stringify(dataOBJ);
  console.log(dataOBJ)
  //alert('資料已送出! 請耐心等候')
  $.ajax({
    url: '/swapFace',
    dataType: 'json', // 預期從server接收的資料型態
    contentType: 'application/json; charset=utf-8', // 要送到server的資料型態
    type: 'post',
    data: objstr,
    success: function (suc_data) {
      alert(suc_data.msg)
    },
    //data:JSON.stringify({n1:"12",n2:"22"}),
    error: function (error) {
      console.error(error)
    }
  });
});

var loaded_data = ''
function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
  document.querySelector('.loader').style.display = "block";
  $.get("/history_input", function (data, status) {
    console.log(data)
    loaded_data = data
    for (var obj of data) {
      var historyList = document.querySelector('.historyList');
      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', 'load_data()');

      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.setAttribute('onclick', 'load_data()');
      list.appendChild(divImgfr);
      list.appendChild(contentBox);
      historyList.appendChild(list);
    }
    document.querySelector('.loader').style.display = "none";
  });
}
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]
  return jwt_raw.split('=')[1]
}

function load_data() {
  var title = document.getElementById("title");
  var linker = document.getElementById("linker");

  myModal.hide()
  tid = event.srcElement.id
  console.log(tid);
  linker.setAttribute('href', `http://${loaded_data.find(item => item.id == tid).link}`)
  linker.setAttribute('target', '_blank')
  $("#linker").html(`http://${loaded_data.find(item => item.id == tid).link}`)
  $("#linker").show();
  $(".linker__box").show();

  let historyItem = loaded_data.filter(item => item.id == tid)[0];
  console.log(historyItem);
  $(".title_new").val(loaded_data.find(item => item.id == tid).name);

  let txtlength = historyItem.text_content.length;
  let imglength = historyItem.image_urls.length;

  subtitleInputs.innerHTML = '';
  imgInputs.innerHTML = '';
  for (let i = 0; i < txtlength; i++) {
    var txtinput = document.createElement("input");
    txtinput.setAttribute('type', 'text');
    txtinput.setAttribute('name', `t${i + 1}`);
    txtinput.value = historyItem.text_content[i];
    txtinput.setAttribute('placeholder', `${i + 1}`);
    txtinput.classList.add('txtsrc', `txtsrc${i + 1}`)
    subtitleInputs.appendChild(txtinput);
  }
  for (let i = 0; i < imglength; i++) {
    var imginput = document.createElement("input");
    imginput.setAttribute('type', 'text');
    imginput.setAttribute('name', `m${i + 1}`);
    imginput.classList.add('imgsrc', `imgsrc${i + 1}`);
    imginput.value = historyItem.image_urls[i];
    imginput.setAttribute('placeholder', `${i + 1}`);
    imgInputs.appendChild(imginput);

    var imgupload = document.createElement("input");
    imgupload.setAttribute('id', `img${i + 1}`);
    imgupload.setAttribute('type', `file`);
    imgupload.classList.add('img_uploader', 'img_up');
    imgInputs.appendChild(imgupload);
    var imguploadlabel = document.createElement("label");
    imguploadlabel.setAttribute('for', `img${i + 1}`);
    imguploadlabel.classList.add('upload-btn');
    imguploadlabel.textContent = '上傳檔案';
    imgInputs.appendChild(imguploadlabel);
  }

}


var subtitleInputs = document.querySelector(".subtitle-inputs");
var imgInputs = document.querySelector(".img-inputs");
let length = 5;
function initial() {
  for (let i = 0; i < length; i++) {
    rendertxtBlock(i + 1);
    renderimgBlock(i + 1);
  }
  console.log(document.querySelectorAll(".txtsrc").length + 1);
}

initial();

var addbtn = document.querySelector(".add");
var addimgbtn = document.querySelector(".addimg");

addbtn.addEventListener('click', addtxtBlock);
addimgbtn.addEventListener('click', addimgBlock);

function addtxtBlock() {
  let newIdx = document.querySelectorAll(".txtsrc").length + 1;
  rendertxtBlock(newIdx);
}

function addimgBlock() {
  let newimgIdx = document.querySelectorAll(".imgsrc").length + 1;
  renderimgBlock(newimgIdx);
}

function rendertxtBlock(i) {
  var txtinput = document.createElement("input");
  txtinput.setAttribute('type', 'text');
  txtinput.setAttribute('name', `t${i}`);
  txtinput.value = "";
  txtinput.setAttribute('placeholder', `${i}`);
  txtinput.classList.add('txtsrc', `txtsrc${i}`)
  subtitleInputs.appendChild(txtinput);
}

function renderimgBlock(i) {
  var imginput = document.createElement("input");
  imginput.setAttribute('type', 'text');
  imginput.setAttribute('name', `m${i}`);
  imginput.classList.add('imgsrc', `imgsrc${i}`);
  imginput.value = "";
  imginput.setAttribute('placeholder', `${i}`);
  imgInputs.appendChild(imginput);

  var imgupload = document.createElement("input");
  imgupload.setAttribute('id', `img${i}`);
  imgupload.setAttribute('type', `file`);
  imgupload.classList.add('img_uploader', 'img_up');
  imgInputs.appendChild(imgupload);
  var imguploadlabel = document.createElement("label");
  imguploadlabel.setAttribute('for', `img${i}`);
  imguploadlabel.classList.add('upload-btn');
  imguploadlabel.textContent = '上傳檔案';
  imgInputs.appendChild(imguploadlabel);
  $('input[type=file]').on('change', prepareUpload);
}


$('.owl-carousel').owlCarousel({
  loop: true,
  margin: 10,
  nav: false,
  mouseDrag: true,
  touchDrag: true,
  smartSpeed: 1000,
  autoplay: true,
  autoplayTimeout: 8000,
  autoplayHoverPause: false,
  responsive: {
    0: {
      items: 1
    },
    600: {
      items: 2
    },
    1000: {
      items: 4
    }
  }
})
