var Wick = Wick || {};

Wick.S3bucketUpload = {
  validExtensionsList: ['jpg', 'jpeg', 'png', 'bmp', 'webp', 'tiff', 'heif', 'heic'],
  isFileExtensionValid: function (file) {
    var fileName = file.name.split('.')
    return Wick.S3bucketUpload.validExtensionsList.includes(fileName[fileName.length - 1].toLowerCase())
  },
  transformXmlError: function (error) {
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(error.responseText, "text/xml");
    var errorMessage = xmlDoc.all[2].innerHTML;
    if (errorMessage === 'Your proposed upload exceeds the maximum allowed size') {
      return 'Unfortunately your document could not be uploaded, as the file exceeds the 5MB limit. Please try again with a file no greater than 5MB.';
    }
    return errorMessage;
  },
  transformError: function (error) {
    if (error.responseXML) {
      return Wick.S3bucketUpload.transformXmlError(error);
    }
    return error.statusText;
  },
  uploadImage: function(file, installerFileName) {
    var isExtesionValid = Wick.S3bucketUpload.isFileExtensionValid(file);
    if (!isExtesionValid) {
      Wick.InstallerForm.filesForm.showErrorNotification(installerFileName, [
        'Unable to attach file. Only JPG, JPEG, PNG, BMP, WEBP, TIFF, HEIC and HEIF image files are supported.'
      ]);

      return;
    }

    Wick.InstallerForm.filesForm.showSpinner();

    const triggerS3Upload = Wick.InstallerForm.recaptchaDecorate("uploadImage", Wick.S3bucketUpload.triggerS3Upload)
    triggerS3Upload(file, installerFileName)
  },
  triggerS3Upload: function (recaptchaToken, file, installerFileName) {
    var hostnames = Wick.InstallerForm.getHostnames();
    var URL_GET_LINK = hostnames.register_url + '/installer/s3-presigned-url';

    $.ajax({
      type: 'GET',
      url: URL_GET_LINK,
      data: {
        'g-recaptcha-response': recaptchaToken
      }
    }).done(function (s3CredsResponse) {
      var URL_POST_LINK = 'https://' + hostnames.upload_domain + '/' + s3CredsResponse.fields.bucket;
      var fileLink = 'https://'+ s3CredsResponse.fields.bucket +'.' + hostnames.upload_domain + '/' + s3CredsResponse.fields.key;

      var form = new FormData();
      form.append('key', s3CredsResponse.fields.key);
      form.append('bucket', s3CredsResponse.fields.bucket);
      form.append('X-Amz-Algorithm', s3CredsResponse.fields['X-Amz-Algorithm']);
      form.append('X-Amz-Credential', s3CredsResponse.fields['X-Amz-Credential']);
      form.append('X-Amz-Date', s3CredsResponse.fields['X-Amz-Date']);
      form.append('X-Amz-Security-Token', s3CredsResponse.fields['X-Amz-Security-Token']);
      form.append('Policy', s3CredsResponse.fields['Policy']);
      form.append('X-Amz-Signature', s3CredsResponse.fields['X-Amz-Signature']);
      form.append('file', file);

      $.ajax({
        async: true,
        type: 'POST',
        url: URL_POST_LINK,
        data: form,
        cache: false,
        processData: false,
        contentType: false
      }).done(function () {
        Wick.InstallerForm.filesForm.hideSpinner();

        Wick.InstallerForm.filesForm.onSuccessFileAdd(file, installerFileName, fileLink);
      }).fail(function (e) {
        var error = Wick.S3bucketUpload.transformError(e);

        Wick.InstallerForm.filesForm.hideSpinner();
        Wick.InstallerForm.filesForm.showErrorNotification(installerFileName, [error]);
      });
    }).fail(function (e) {
      var error = Wick.S3bucketUpload.transformError(e);

      Wick.InstallerForm.filesForm.hideSpinner();
      Wick.InstallerForm.filesForm.showErrorNotification(installerFileName, [error]);
    })
  }
};
