const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());

name_hash = params['id']
dataArr=''


function get_script() {
  var url = "uploadmp3";
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);

  xhr.setRequestHeader("accept", "application/json");
  xhr.setRequestHeader("Content-Type", "application/json");

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        dataArr = xhr.responseText.split(',');
    }};
  var data = `{"name_hash": `+name_hash+`}`;
  xhr.send(data);
}
get_script();

var srcInput = document.querySelector(".msrcParent");
for (step = 0; step < dataArr.length; step++) {
  console.log(dataArr[step])
  var pdiv = document.createElement('div');
  pdiv.classList.add('subtitle-inputs')
  

  var rawSrc = document.createElement("input");
  rawSrc.setAttribute('type', 'text');
  rawSrc.value = dataArr[step];
  rawSrc.style.width = "47%";

  var mSrc = document.createElement("input");
  mSrc.setAttribute('type', 'text');
  mSrc.setAttribute('id', `s${step }`);
  mSrc.style.width = "47%";
  pdiv.appendChild(rawSrc)
  pdiv.appendChild(mSrc)

  srcInput.appendChild(pdiv)
    
}


$(".confirmbtn" ).click(function() {
  for (i = 0; i < dataArr.length; i++) {
    if ($(`#s${i }`).val()!=''){
      dataArr[i]=$(`#s${i }`).val();
    }
  }
  sendString = dataArr.join(',');

  var url = "http://www.choozmo.com:8889/updateScript";

  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);
  
  xhr.setRequestHeader("accept", "application/json");
  xhr.setRequestHeader("Content-Type", "application/json");
  
  xhr.onreadystatechange = function () {
     if (xhr.readyState === 4) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        alert('請等待line通知');
     }};
  
  var data = `{"name_hash":`+name_hash+ `,"scriptStr": `+sendString+`}`;
  
  xhr.send(data);
  


});