class FileUpload {
  constructor(input) {
    this.input = input;
  }

  upload() {
    Array.from(this.input.files).forEach(file => {
      this.create_progress_bar(file);
      this.upload_file(file);
    });

    this.input.value = '';
  }

  upload_file(file) {
    var formData = new FormData();
    formData.append('file', file);
    formData.append('filename', file.name);

    $('.filename[data-name="' + file.name + '"]').text(file.name);
    $('.textbox[data-name="' + file.name + '"]').text("Uploading file");

    $.ajaxSetup({
      headers: {
        "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value,
      }
    });

    var self = this; // Preserve reference to 'this'

    $.ajax({
      xhr: function () {
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', function (e) {
          if (e.lengthComputable) {
            var percent = Math.round((e.loaded / e.total) * 100);
            $('.progress-bar[data-name="' + file.name + '"]').css('width', percent + '%');
            $('.loaderInfo[data-name="' + file.name + '"] .progress-percent').text(percent + '%');
          }
        });
        return xhr;
      },

      url: '/add/fileUploader/',
      type: 'POST',
      dataType: 'json',
      cache: false,
      processData: false,
      contentType: false,
      data: formData,
      error: function (xhr) {
        alert(xhr.statusText);
      },
      success: function (res) {
        $('.textbox[data-name="' + file.name + '"]').text(res.data);
        console.log('File uploaded to:', res.existingPath);

        // Add the uploaded file path as an option in the select tag
        var option = '<option value="' + res.existingPath +  '" selected>' + res.existingPath + '</option>';
        $('#filePathInput').append(option);
      }
    });
  }

  create_progress_bar(file) {
    var progress = `
                      <div class="w-[100%] bg-gray-400 bg-opacity-70 overflow-hidden rounded-md h-[60px] progress relative">
                          <div class="flex justify-start items-center gap-2 progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%" data-name="${file.name}">
                          </div>
                          <div class="w-full inset-0 z-50 absolute flex justify-between items-center px-3 py-3 loaderInfo" data-name="${file.name}">
                            <div class="flex justify-start items-center gap-2">
                              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="w-6 h-6 text-white" fill="none">
                              <path d="M16 17L9 17" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
                              <path d="M16 13L13 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
                              <path d="M20.5 14C20.5 17.7712 20.5 19.6569 19.2552 20.8284C18.0104 22 16.0069 22 12 22H11.2273C7.96607 22 6.33546 22 5.20307 21.2022C4.87862 20.9736 4.59058 20.7025 4.3477 20.3971C3.5 19.3313 3.5 17.7966 3.5 14.7273V12.1818C3.5 9.21865 3.5 7.73706 3.96894 6.55375C4.72281 4.65142 6.31714 3.15088 8.33836 2.44135C9.59563 2 11.1698 2 14.3182 2C16.1173 2 17.0168 2 17.7352 2.2522C18.8902 2.65765 19.8012 3.5151 20.232 4.60214C20.5 5.27832 20.5 6.12494 20.5 7.81818V14Z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" />
                              <path d="M3.5 12C3.5 10.1591 4.99238 8.66667 6.83333 8.66667C7.49912 8.66667 8.28404 8.78333 8.93137 8.60988C9.50652 8.45576 9.95576 8.00652 10.1099 7.43136C10.2833 6.78404 10.1667 5.99912 10.1667 5.33333C10.1667 3.49238 11.6591 2 13.5 2" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
                            </svg>

                            <p class="filename text-white text-sm s:text-base" data-name="${file.name}"></p>
                          </div>

                          <div class="flex justify-end items-center gap-1"> 
                            <p class="textbox text-white" data-name="${file.name}"></p>
                            <p class="text-white">-</p>
                            <p class="progress-percent text-white" data-name="${file.name}">0%</p>
                          </div>
                          </div>
                      </div>`;
    $('#uploaded_files').append(progress);
  }
}

(function ($) {
  $('#fileupload').on('change', function (event) {
    var uploader = new FileUpload(this);
    uploader.upload();
  });
})(jQuery);
