/* eslint-disable no-undef */
let list;
let attachment;
let removeMedia = [];

var rowPage = 9;

async function paginationSummary(pageSize,page,id,token){
  var res = await fetch(`/api/materials?filters[pintar_summary][id][$eq]=${id}&pagination[page]=${page}&pagination[pageSize]=${pageSize}&populate=*`,{
      headers: {
          'Authorization': `Bearer ${token}`
      },
  });
  if(res.ok){
      var obj = await res.json();
      $("#summaryTable tbody").empty();
      $("#summaryPagination").empty();
      $("#summaryPagination").append(`
          <li class="page-item ${obj.meta.pagination.page==1?'disabled':''}">
              <a value="${obj.meta.pagination.page-1}" class="page-link" href="#" tabindex="-1">
              <i class="fas fa-angle-left"></i>
              <span class="sr-only">Previous</span>
              </a>
          </li>
      `);
      for(var i =1; i <= obj.meta.pagination.pageCount;i++){
          $("#summaryPagination").append(`
              <li class="page-item ${obj.meta.pagination.page==i?"active":''}"><a value="${i}" class="page-link" href="#">${i}</a></li>
          `);
      }
      $("#summaryPagination").append(`
          <li class="page-item ${obj.meta.pagination.page==obj.meta.pagination.pageCount?'disabled':''}">
              <a value="${obj.meta.pagination.page+1}" class="page-link" href="#">
              <i class="fas fa-angle-right"></i>
              <span class="sr-only">Next</span>
              </a>
          </li>
      `);
      obj.data.forEach((i,indx)=>{
        var imgs = '-';
        if(i.attributes.Images.data){
          imgs = '';
          i.attributes.Images.data.forEach(img=>imgs+=`<img style="padding:5px;width:100px;" src="${img.attributes.url}"/><br/>`);
        }
          $("#summaryTable tbody").append(`
          <tr>
          <th scope="row">${((obj.meta.pagination.page-1)*pageSize)+indx+1}</th>
          <td>${i.attributes.company.data.attributes.Name}</td>
          <td>${i.attributes.division.data.attributes.Name}</td>
          <td>${i.attributes.Title??'-'}</td>
          <td>${imgs}</td>
          <td>${(i.attributes.Video.data)?"<a href='"+i.attributes.Video.data.attributes.url+"' target='_blank'>video</a>":'-'}</td>
          <td>${i.attributes.Name??'-'}</td>
          <td>${(i.attributes.participants.data)?i.attributes.participants.data.length:''}</td>
          </tr>
          `);
      });

      //set callback pagination
      $('#summaryPagination .page-link').off('click');
      $("#summaryPagination .page-link").click(async(e)=>{
          e.preventDefault();
          paginationSummary(pageSize,$(e.target.closest('a')).attr('value'),id,token);
      });
  }
  else{
      showAlert('error','Gagal menarik data. Harap login ulang!');
  }
}

$('#modal-summary').on('shown.bs.modal', async function(event) {
  $("#summaryMaterial").text($(event.relatedTarget).attr('material'));
  var id = $(event.relatedTarget).attr('summary');
  if(id){
      var getToken = await fetch(`/session/key?s=jwt`);
      if(getToken.ok){
        paginationSummary(rowPage,1,id,await getToken.text());
      }
      else{
          showAlert('error','Gagal menarik data divisi. Harap login ulang!');
      }
  }
  else{
      showAlert("error","Terjadi kesalahan saat menarik data!");
  }
})

$('#companySelect').change(async e => {
  if (e.target.value && e.target.value != '') {
    $('#divisionSelect').removeAttr('disabled');
    const getToken = await fetch(`/session/key?s=jwt`);
    if (getToken.ok) {
      const token = await getToken.text();
      const res = await fetch(`/api/divisions${(e.target.value=='All')?'':"?filters[companies][id][$in]="+e.target.value}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (res.ok) {
        const obj = await res.json();
        $('#divisionSelect').empty();
        $('#divisionSelect').append('<option  value="All">Semua</option>');
        obj.data.forEach(i => {
          $('#divisionSelect').append(`<option  value="${i.id}">${i.attributes.Name}</option>`);
        });
      }
    } else {
      showAlert('error', 'Gagal menarik data divisi. Harap login ulang!');
    }
  } else {
    $('#divisionSelect').attr('disabled', 'disabled');
  }
});

$('.editMaterial').click(async e => {
  e.preventDefault();
  const getRole = await fetch(`/session/key?s=role`);
    if (getRole.ok) {
      var role = JSON.parse(await getRole.text());
      // if(role.name == 'Editor'||role.name == 'Admin'){
        const id = $(e.target.closest('a')).attr('value');
        $("input.categoryField").val($(e.target.closest('a')).attr('category'));
        $('#selMaterial').val(id);
        $('#modal-form').attr('operation', 'edit');
        $('#modal-form').modal('show');
        showForm('Sharing');
      // }
      // else{
      //   showAlert('error', "Tidak diperbolehkan untuk mengubah data. Minta ijin dari admin terlebih dahulu");
      // }
    }
    else{
      window.location = '/logout'
    }
});

$('.completeMaterial').click(async e => {
  e.preventDefault();
  const id = $(e.target.closest('a')).attr('value');
  $("input.categoryField").val($(e.target.closest('a')).attr('category'));
  $('#selMaterial').val(id);
  $('#modal-form').attr('operation', 'complete');
  $('#modal-form').modal('show');
  showForm('Sharing');
});

$('.resetMaterial').click(async e => {
  e.preventDefault();
  const id = $(e.target.closest('a')).attr('value');
  loading(70, true);
    const getToken = await fetch(`/session/key?s=jwt`);
    if (getToken.ok) {
      const token = await getToken.text();
      const res = await fetch(`/api/resetMaterial/${id}`, {
        method: 'PUT',
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (res.ok) {
        location.reload();
      } else {
        loading(0, false);
        try {
          const obj = await res.json();
          if(obj.error.message.includes('Forbidden')){
            showAlert('error', "Tidak diperbolehkan untuk mengubah data. Minta ijin dari admin terlebih dahulu");
          }
          else showAlert('error', obj.error.message);
        } catch (e) {
          showAlert('error', 'Tidak dapat mereset materi. Terjadi kesalahan!');
        }
      }
    } else {
      loading(0, false);
      showAlert('error', 'Gagal menarik data divisi. Harap login ulang!');
    }
});



$('.removeMaterial').click(async e => {
  e.preventDefault();
  const id = $(e.target.closest('a')).attr('value');
  if (confirm('delete this material?')) {
    loading(70, true);
    const getToken = await fetch(`/session/key?s=jwt`);
    if (getToken.ok) {
      const token = await getToken.text();
      const res = await fetch(`/api/materials/${id}`, {
        method: 'DELETE',
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (res.ok) {
        location.reload();
      } else {
        loading(0, false);

        try {
          const obj = await res.json();
          if(obj.error.message.includes('Forbidden')){
            showAlert('error', "Tidak diperbolehkan untuk mengubah data. Minta ijin dari admin terlebih dahulu");
          }
          else showAlert('error', obj.error.message);
        } catch (e) {
          showAlert('error', 'Tidak dapat menghapus materi. Terjadi kesalahan!');
        }
      }
    } else {
      loading(0, false);
      showAlert('error', 'Gagal menarik data divisi. Harap login ulang!');
    }
  }
});

function showForm(dialog) {
  $("#pickForm input[name='Category']").val(dialog);
  $("#pickForm span.categoryTitle").text(dialog);
  $('#pickForm').removeClass('hide');
  $('#pickCategory').addClass('hide');
}

function hideform() {
  $("#pickForm input[name='Category']").val('');
  $("#pickForm span.categoryTitle").text('');
  $('#pickForm').addClass('hide');
  $('#pickCategory').removeClass('hide');
}

$('input[type=file]').change(function(e) {
  var files = e.target.files;
  if (files && [...files].filter(i=>i.size>104857600).length >0) {
    showAlert(
      'error',
      'File yang dipilih terlalu besar Max(100 MB)! Compress atau potong file yang ingin di upload!'
    );
    e.target.value = '';
  }
});

function removeUpload(e, listFile) {
  let li = $(e.target).parent();
  
  while  (li[0].localName != 'li') {
    li = $(li).parent();
  }
  if (li.attr('status') == 'uploaded') removeMedia.push(li.val());
  else {
    for (let i = 0; i < listFile.items.length; i++) {
      if (listFile.files[i].name.replace(/["']/g, '') == li.attr('name')) {
        listFile.items.remove(i);
      }
    }
  }
  li.remove();
}

$('#modal-form').on('hide.bs.modal', function(e) {
  if($(e.target).hasClass('modal')){
    hideform();
    $('#modal-form').attr('operation', '');
    $('#uploadedAttachment').empty();
    $('#uploadedFile').empty();
    $('#modal-form input[name=Title]').removeAttr('disabled');
    $(`#modal-form input[name=Start_Date]`).removeAttr('disabled');
    $(`#modal-form input[name=End_Date]`).removeAttr('disabled');
    $('#modal-form textarea[name=Description]').removeAttr('disabled');
    $('#modal-form input#formAttachment').closest('.form-group').show();
    $(`#modal-form input#thumbnail`).closest('.form-group').show();
    $('#modal-form select[name=company]').closest('.form-group').show();
    $('#modal-form select[name=division]').closest('.form-group').show();
    $("#thumbnailSelected").remove();
    $("#videoSelected").remove();
    $(`#modal-form .completeData`).addClass('hide');
  }
});

$('#modal-form').on('shown.bs.modal', async function() {
  removeMedia = [];
  let materialData;
  $("#modal-form input[type!='hidden']").val('');
  $('#modal-form select').val('');
  $('#modal-form select[name=division]').attr('disabled','disabled');
  $('#modal-form textarea').html('');
  $('#modal-form textarea').val('');
  const container = document.getElementById('participantCounter');
  if(container)container.innerHTML = '';
  $("#modal-form input[name='ParticipantList']").val('');
  list = new DataTransfer();
  attachment = new DataTransfer();
  if ($('#modal-form').attr('operation') == 'edit' || $('#modal-form').attr('operation') == 'complete') {
    loading(0, true);
    const getToken = await fetch(`/session/key?s=jwt`);
    if (getToken.ok) {
      const token = await getToken.text();
      const res = await fetch(`/api/materials/${$('#selMaterial').val()}?populate=*`, {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      loading(100, true);
      if (res.ok) {
        loading(0, false);
        try {
          let obj = await res.json();
          obj = obj.data.attributes;
          if(obj.Presented) obj.Presented = moment(obj.Presented,'DD MMM YYYY').format('YYYY-MM-DD');
          materialData = obj;
          var form = $("#formCreateAdmin").length>0?'formCreateAdmin':'formCreate';
          $(`#${form} select[name=company]`).closest('.form-group').hide();
          $(`#${form} select[name=division]`).closest('.form-group').hide();
          if(obj.Presented || $('#modal-form').attr('operation') == 'complete')$(`#${form} .completeData`).removeClass('hide');
          if($('#modal-form').attr('operation') =='complete'){
            $(`#${form} input[name=Title]`).attr('disabled','');
            $(`#${form} input[name=Start_Date]`).attr('disabled','');
            $(`#${form} input[name=End_Date]`).attr('disabled','');
            $(`#${form} textarea[name=Description]`).attr('disabled','');
            $(`#${form} input#formAttachment`).closest('.form-group').hide();
            $(`#${form} input#thumbnail`).closest('.form-group').hide();
          }
          $(`#${form} input[name="Category"]`).val(obj.Category);
          Object.keys(obj).forEach(async i => {
            if(obj[i]&&obj[i].data){
                if (typeof obj[i] === 'object' && !(obj[i].data instanceof Array)) {
                if (!obj[i].data.attributes.mime) {
                  $(`#${form} [name='${i}']`).val(obj[i].data.id);
                  if (i == 'company') {
                    const res = await fetch(
                      `/api/divisions?filters[companies][id][$in]=${obj[i].data.id}`,
                      {
                        headers: {
                          Authorization: `Bearer ${token}`,
                        },
                      }
                    );
                    if (res.ok) {
                      const resp = await res.json();
                      $(`#${form} .modalDivisionSelect`).empty();
                      $(`#${form} .modalDivisionSelect`).append(
                        $(`#${form} .categoryField`).val()=='Pintar'
                        ?'<option value="All">Semua</option>'
                        :'<option value="">Pilih divisi dari list</option>'
                      );
                      resp.data.forEach(item => {
                        $(`#${form} .modalDivisionSelect`).append(
                          `<option ${item.id == (obj.division.data?obj.division.data.id:'') ? 'selected' : ''} value="${
                            item.id
                          }">${item.attributes.Name}</option>`
                        );
                      });
                      $(`#${form} .modalDivisionSelect`).removeAttr('disabled');
                    }
                  }
                } else {
                  if(i == 'Video'){
                    $(`#${form} input#videoFile`).after(
                      `<small id="videoSelected" style="line-height: 4em;">current video : ${obj[i].data.attributes.name}</small>`
                    );
                  }
                  else if(i == 'Thumbnail'){
                    $(`#${form} input#thumbnail`).after(
                      `<small id="thumbnailSelected" style="line-height: 4em;">current Thumbnail : ${obj[i].data.attributes.name}</small>`
                    );
                  }
                }
                } else if (obj[i].data instanceof Array) {
                  if (i == 'participants') {
                    const aoa = obj[i].data.map(o => o.attributes);
                    const container = document.getElementById('participantCounter');
                    if(container)container.innerHTML = `${aoa.length} Participant(s)`;
                    $(`#${form} input[name='ParticipantList']`).val(JSON.stringify(aoa));
                  } else if (i == 'Images') {
                    obj[i].data.forEach(async thumbnails => {
                      $(`#${form} #uploadedFile`).append(
                        `<li status='uploaded' value='${
                          thumbnails.id
                        }' name='${thumbnails.attributes.name.replace(/["']/g, '')}'>${
                          thumbnails.attributes.name
                        }
                                                    <button type="button" class="btn-close btn-icon removeUpload" onclick="removeUpload(event,list)" aria-label="Close">
                                                      <span class="btn-inner--icon"><i class="ni ni-fat-remove"></i></span>
                                                    </button>
                                                </li>`
                      );
                    });
                  } else if (i == 'Attachments') {
                    obj[i].data.forEach(async attachments => {
                      $(`#${form} #uploadedAttachment`).append(
                        `<li status='uploaded' value='${
                          attachments.id
                        }' name="${attachments.attributes.name.replace(/["']/g, '')}">${
                          attachments.attributes.name
                        }
                                                    <button type="button" class="btn-close btn-icon removeUpload" onclick="removeUpload(event,attachment)" aria-label="Close">
                                                      <span class="btn-inner--icon"><i class="ni ni-fat-remove"></i></span>
                                                    </button>
                                                </li>`
                      );
                    });
                  }
                } 
            }
            else {
              if($(`#${form} [name='${i}']`).length>0)$(`#modal-form [name='${i}']`).val(obj[i]);
            }
            
          });
        } catch (e) {
          $('#loading').hide();
          console.log(e);
        }
      } else {
        loading(0, false);
        showAlert('error', 'Tidak dapat mencari data materi. Terjadi kesalahan!');
      }
    } else {
      loading(0, false);
      showAlert('error', 'Terjadi kesalahan! Harap coba login kembail atau hubungi admin!');
    }
  }
  $('#formCreate').off('submit');
  $('#formCreateAdmin').off('submit');

  $('#formCreate').submit(async event => {
    event.preventDefault();
    clearAlert();
    var el = this;
    $(el).find(':input[type=submit]').prop('disabled', true);
    if ($('#modal-form').attr('operation') == 'edit'|| $('#modal-form').attr('operation') == 'complete') {
      if (
        (materialData.Presented || $('#modal-form').attr('operation') == 'complete')
        ?($(event.target)
          .serializeArray()
          .filter(item => item.value == '').length > 0)
        :($(event.target)
        .serializeArray()
        .filter(item => item.value == '' && !($("#modal-form .completeData input").map((idx,i)=>$(i).attr("name")).toArray().includes(item.name))).length > 0)
      ) {
        showAlert('error', 'Cek kembali data yang belum diisi!');
      }
      else if ($('ul#uploadedFile li').length < 3 || $('ul#uploadedAttachment li').length <= 0) {
        showAlert('error', 'File yang dibutuhkan tidak lengkap!');
      } else {
        loading(10, true);
        var getToken = await fetch(`/session/key?s=jwt`);
        if (getToken.ok) {
          const formData = new FormData();
          var obj = {};
          $(event.target)
            .serializeArray()
            .forEach(element => {
              try {
                obj[element.name] = JSON.parse(element.value);
              } catch (e) {
                obj[element.name] = element.value;
              }
            });
          if(materialData && materialData.Images.data){
            const Images = materialData.Images.data.map(item => item.id);
            if(removeMedia && removeMedia.length>0 && removeMedia.some(r=> Images.includes(r))){
              obj.Images = Images.filter(item => !removeMedia.includes(item));
            }
          }

          for (let i = 0; i < list.files.length; i++) {
            const file = list.files[i];
            formData.append(`files.Images`, file, file.name);
          }

          if(materialData && materialData.Attachments){
            const Attachments = materialData.Attachments.data.map(item => item.id);
            if(removeMedia && removeMedia.length>0 && removeMedia.some(r=> Attachments.includes(r))){
              obj.Attachments = Attachments.filter(item => !removeMedia.includes(item));
            }
          }

          for (let i = 0; i < attachment.files.length; i++) {
            const file = attachment.files[i];
            formData.append(`files.Attachments`, file, file.name);
          }

          if ($('#videoFile').prop('files').length > 0) {
            obj.Video = [];
            formData.append(
              `files.Video`,
              $('#videoFile').prop('files')[0],
              $('#videoFile').prop('files')[0].name
            );
          }

          if($('#thumbnail').prop('files').length>0){
            obj.Thumbnail = [];
            formData.append(
              `files.Thumbnail`,
              $('#thumbnail').prop('files')[0],
              $('#thumbnail').prop('files')[0].name
            );
          }

          const request = new XMLHttpRequest();
          request.upload.onprogress = function(evt) {
            if (evt.lengthComputable) {
              const percentComplete = parseInt((evt.loaded / evt.total) * 100);
              loading(percentComplete, true);
            }
          };
          request.onreadystatechange = function() {
            if (request.readyState == 4) {
              loading(0, false);
              if (request.status == 200) {
                location.reload();
              } else {
                showAlert('error', 'Terjadi kesalahan! Harap coba login kembali / hubungi admin!');
              }
            }
          };

          formData.append('data', JSON.stringify(obj));
          if($('#modal-form').attr('operation')=='edit') request.open('PUT', `/api/materials/${$('#selMaterial').val()}`);
          else request.open('PUT', `/api/saveMaterial/${$('#selMaterial').val()}`);
          request.setRequestHeader('Authorization', `Bearer ${await getToken.text()}`);
          request.send(formData);
        } else {
          loading(0, false);
          showAlert('error', 'Terjadi kesalahan. Harap login kembali!');
        }
      }
    } else{
      if (
        $(event.target)
          .serializeArray()
          .filter(item => item.value == '').length > 0
    ) {
      showAlert('error', 'Cek kembali data yang belum diisi!');
    } else if (
      $('input#videoFile').prop('files').length <= 0 ||
      list.files.length <= 0 ||
      attachment.files.length <= 0
    ) {
      showAlert('error', 'File yang dibutuhkan tidak lengkap!');
    } else {
      loading(0, true);
      var getToken = await fetch(`/session/key?s=jwt`);
      if (getToken.ok) {
        var obj = {};
        $(event.target)
          .serializeArray()
          .forEach(element => {
            try {
              obj[element.name] = JSON.parse(element.value);
            } catch (e) {
              obj[element.name] = element.value;
            }
          });
        const formData = new FormData();
        formData.append('data', JSON.stringify(obj));
        for (let i = 0; i < list.files.length; i++) {
          const file = list.files[i];
          formData.append(`files.Images`, file, file.name);
        }
        for (let i = 0; i < attachment.files.length; i++) {
          const file = attachment.files[i];
          formData.append(`files.Attachments`, file, file.name);
        }
        formData.append(
          `files.Video`,
          $('#videoFile').prop('files')[0],
          $('#videoFile').prop('files')[0].name
        );

        formData.append(
          `files.Thumbnail`,
          $('#thumbnail').prop('files')[0],
          $('#thumbnail').prop('files')[0].name
        );
        

        const request = new XMLHttpRequest();
        request.upload.onprogress = function(evt) {
          if (evt.lengthComputable) {
            const percentComplete = parseInt((evt.loaded / evt.total) * 100);
            loading(percentComplete, true);
          }
        };
        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            loading(0, false);
            if (request.status == 200) {
              location.reload();
            } else {
              showAlert('error', 'Terjadi kesalahan! Harap coba login kembali / hubungi admin!');
            }
          }
        };
        request.open('POST', '/api/materials');
        request.setRequestHeader('Authorization', `Bearer ${await getToken.text()}`);
        request.send(formData);
      } else {
        loading(0, false);
        showAlert('error', 'Terjadi kesalahan. Harap login kembali!');
      }
    }
    } 
    setTimeout(function(){$(el).find(':input[type=submit]').prop('disabled', false);},3000);
  });

  $('#formCreateAdmin').submit(async event => {
    event.preventDefault();
    clearAlert();
    var el = this;
    $(el).find(':input[type=submit]').prop('disabled', true);
    setTimeout(function(){$(el).find(':input[type=submit]').prop('disabled', false);},3000);
    if ($('#modal-form').attr('operation') == 'edit'|| $('#modal-form').attr('operation') == 'complete') {
      if (
        (materialData.Presented || $('#modal-form').attr('operation') == 'complete')
        ?($(event.target)
          .serializeArray()
          .filter(item => item.value == '').length > 0)
        :($(event.target)
        .serializeArray()
        .filter(item => item.value == '' && !($("#modal-form .completeData input").map((idx,i)=>$(i).attr("name")).toArray().includes(item.name))).length > 0)
      ) {
        showAlert('error', 'Cek kembali data yang belum diisi!');
      }
      // else if ($('ul#uploadedFile li').length <= 0 || $('ul#uploadedAttachment li').length <= 0) {
        else if(((materialData.Presented || $('#modal-form').attr('operation') == 'complete')?$("#modal-form input[type=file][multiple=multiple]"):$("#modal-form input[type=file][multiple=multiple]").not(".completeData input[type=file][multiple=multiple]")).filter((i,k)=> $(k).parent().next().children('li').length<=0).length>0) {
          showAlert('error', 'File yang dibutuhkan tidak lengkap!');
      } else {
        loading(10, true);
        var getToken = await fetch(`/session/key?s=jwt`);
        if (getToken.ok) {
          const formData = new FormData();
          var obj = {};
          $(event.target)
            .serializeArray()
            .forEach(element => {
              try {
                if(element.value[0]=='{'){
                  obj[element.name] = JSON.parse(element.value);
                }
                else if(element.value.includes('/')){
                  obj[element.name] = moment(element.value,'MM/DD/YYYY').format('YYYY-MM-DD');
                }
                else{
                  obj[element.name] = element.value;
                }
              } catch (e) {
                obj[element.name] = `"${element.value}"`;
              }
            });
          if(!$(`#modal-form .completeData`).hasClass('hide')){
            if(materialData.Images.data){
              const Images = materialData.Images.data.map(item => item.id);
              if(removeMedia && removeMedia.length>0 && removeMedia.some(r=> Images.includes(r))){
                obj.Images = Images.filter(item => !removeMedia.includes(item));
              }
            }
            for (let i = 0; i < list.files.length; i++) {
              const file = list.files[i];
              formData.append(`files.Images`, file, file.name);
            }

            if($('#videoFile').prop('files').length>0){
              obj.Video = [];
              formData.append(
                `files.Video`,
                $('#videoFile').prop('files')[0],
                $('#videoFile').prop('files')[0].name
              );
            }
          }
          else{
            delete obj['ParticipantList'];
          }
          const Attachments = materialData.Attachments.data.map(item => item.id);
          if(removeMedia && removeMedia.length>0 && removeMedia.some(r=> Attachments.includes(r))){
            obj.Attachments = Attachments.filter(item => !removeMedia.includes(item));
          }

          for (let i = 0; i < attachment.files.length; i++) {
            const file = attachment.files[i];
            formData.append(`files.Attachments`, file, file.name);
          }
          
          if($('#thumbnail').prop('files').length>0){
            obj.Thumbnail = [];
            formData.append(
              `files.Thumbnail`,
              $('#thumbnail').prop('files')[0],
              $('#thumbnail').prop('files')[0].name
            );
          }
          const request = new XMLHttpRequest();
          request.upload.onprogress = function(evt) {
            if (evt.lengthComputable) {
              const percentComplete = parseInt((evt.loaded / evt.total) * 100);
              loading(percentComplete, true);
            }
          };
          request.onreadystatechange = function() {
            // console.log(this.responseText,request.readyState,request.status);
            if (request.readyState == 4) {
              loading(0, false);
              if (request.status == 200) {
                location.reload();
              } else {
                console.log(this.responseURL,this.responseText);
                showAlert('error', 'Terjadi kesalahan! Harap coba login kembali / hubungi admin!');
              }
            }
          };
          formData.append('data', JSON.stringify(obj));
          if($('#modal-form').attr('operation')=='edit') request.open('PUT', `/api/materials/${$('#selMaterial').val()}`);
          else request.open('PUT', `/api/saveMaterial/${$('#selMaterial').val()}`);
          request.setRequestHeader('Authorization', `Bearer ${await getToken.text()}`);
          request.send(formData);
        } else {
          loading(0, false);
          showAlert('error', 'Terjadi kesalahan. Harap login kembali!');
        }
      }
    } else {
      if (
        $(event.target)
          .serializeArray()
          .filter(item => item.value == '' && !($("#modal-form .completeData input").map((idx,i)=>$(i).attr("name")).toArray().includes(item.name))).length > 0
      ) {
        showAlert('error', 'Cek kembali data yang belum diisi!');
      } else {
        loading(0, true);
        var getToken = await fetch(`/session/key?s=jwt`);
        if (getToken.ok) {
          var obj = {};
          $(event.target)
            .serializeArray()
            .forEach(element => {
              try {
                if(element.value[0]=='{'){
                  obj[element.name] = JSON.parse(element.value);
                }
                else{
                  obj[element.name] = element.value;
                }
              } catch (e) {
                obj[element.name] = element.value;
              }
            });
          // console.log(JSON.stringify(obj));
          const formData = new FormData();
          formData.append('data', JSON.stringify(obj));
          // for (let i = 0; i < list.files.length; i++) {
          //   const file = list.files[i];
          //   formData.append(`files.Images`, file, file.name);
          // }
          for (let i = 0; i < attachment.files.length; i++) {
            const file = attachment.files[i];
            formData.append(`files.Attachments`, file, file.name);
          }
          
          formData.append(
            `files.Thumbnail`,
            $('#thumbnail').prop('files')[0],
            $('#thumbnail').prop('files')[0].name
          );
        
          const request = new XMLHttpRequest();
          request.upload.onprogress = function(evt) {
            if (evt.lengthComputable) {
              const percentComplete = parseInt((evt.loaded / evt.total) * 100);
              loading(percentComplete, true);
            }
          };
          request.onreadystatechange = function() {
            if (request.readyState == 4) {
              loading(0, false);
              if (request.status == 200) {
                location.reload();
              } else {
                console.log(this.responseURL,this.responseText);
                showAlert('error', 'Terjadi kesalahan! Harap coba login kembali / hubungi admin!');
              }
            }
          };
          request.open('POST', '/api/materials');
          request.setRequestHeader('Authorization', `Bearer ${await getToken.text()}`);
          request.send(formData);
        } else {
          loading(0, false);
          showAlert('error', 'Terjadi kesalahan. Harap login kembali!');
        }
      }
    }
  });

  $('#formFile').change(event => {
    if (event.target.files.length > 0) {
      for (let i = 0; i < event.target.files.length; i++) {
        list.items.add(event.target.files[i]);
        $('#uploadedFile').append(
          `<li name='${event.target.files[i].name.replace(/["']/g, '')}'>${
            event.target.files[i].name
          }
              <button type="button" class="btn btn-secondary btn-sm btn-close btn-icon removeUpload" onclick="removeUpload(event,list)" aria-label="Close"><i class="ni ni-fat-remove"></i></button>
          </li>`
        );
      }
      $(event.target).val('');
    }
  });

  $('#formAttachment').change(event => {
    if (event.target.files.length > 0) {
      for (let i = 0; i < event.target.files.length; i++) {
        attachment.items.add(event.target.files[i]);
        $('#uploadedAttachment').append(
          `<li name='${event.target.files[i].name.replace(/["']/g, '')}'>${
            event.target.files[i].name
          }
                        <button type="button" class="btn btn-secondary btn-sm btn-close removeUpload" onclick="removeUpload(event,attachment)" aria-label="Close"><i class="ni ni-fat-remove"></i></button>
                    </li>`
        );
      }
      $(event.target).val('');
    }
  });

  $('#formAttachmentPintar').change(event => {
    if (event.target.files.length > 0) {
      for (let i = 0; i < event.target.files.length; i++) {
        attachment.items.add(event.target.files[i]);
        $('#uploadedAttachmentPintar').append(
          `<li name='${event.target.files[i].name.replace(/["']/g, '')}'>${
            event.target.files[i].name
          }
                        <button type="button" class="btn btn-secondary btn-sm btn-close removeUpload" onclick="removeUpload(event,attachment)" aria-label="Close"><i class="ni ni-fat-remove"></i></button>
                    </li>`
        );
      }
      $(event.target).val('');
    }
  });

  $('#formFilePintar').change(event => {
    if (event.target.files.length > 0) {
      for (let i = 0; i < event.target.files.length; i++) {
        list.items.add(event.target.files[i]);
        $('#uploadedFilePintar').append(
          `<li name='${event.target.files[i].name.replace(/["']/g, '')}'>${
            event.target.files[i].name
          }
              <button type="button" class="btn btn-secondary btn-sm btn-close removeUpload" onclick="removeUpload(event,list)" aria-label="Close"><i class="ni ni-fat-remove"></i></button>
          </li>`
        );
      }
      $(event.target).val('');
    }
  });

  $('#join-form').change(async event => {
    const file = event.target.files[0];
    const data = await file.arrayBuffer();
    const workbook = XLSX.read(data);
    const aoa = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], { header: 0 });
    const container = document.getElementById('participantCounter');
    container.innerHTML = `${aoa.length} Participant(s)`;
    $("input[name='ParticipantList']").val(JSON.stringify(aoa));
  });
});

$('#btnDisabled').click(e => {
  e.preventDefault();
  showAlert('error',"Hanya Admin yang dapat membuat Materi Sabtu Pintar!");
});


$('#btnPintar').click(e => {
  e.preventDefault();
  showForm('Pintar');
});

$('#btnSharing').click(e => {
  e.preventDefault();
  showForm('Sharing');
});
