/**
 * RMBG PRO - Admin product page JS
 */

(function () {
  function showMessage(type, message) {
    var $box = $('#rmbgpro-messages');
    var klass = type === 'success' ? 'alert-success' : 'alert-danger';
    $box.html('<div class="alert ' + klass + '">' + message + '</div>');
  }

  function setLoading(isLoading) {
    $('#rmbgpro-spinner').toggle(isLoading);
    $('#rmbgpro-remove-bg').prop('disabled', isLoading || !(window.rmbgpro && window.rmbgpro.enabled));
    $('#rmbgpro-image-select').prop('disabled', isLoading);
  }

  function getSelectedImageIds() {
    var ids = [];
    $('#rmbgpro-image-select option:selected').each(function () {
      var v = parseInt($(this).val(), 10);
      if (v) {
        ids.push(v);
      }
    });
    return ids;
  }

  function processOne(idImage) {
    return $.ajax({
      url: window.rmbgpro.ajaxUrl,
      method: 'POST',
      dataType: 'json',
      data: {
        ajax: 1,
        action: 'removeBackground',
        id_image: idImage
      }
    });
  }

  function processQueue(state) {
    if (!state.queue.length) {
      return $.Deferred().resolve(state).promise();
    }

    var idImage = state.queue.shift();
    showMessage('success', 'Processing ' + state.done + '/' + state.total + ' (image #' + idImage + ')...');

    return processOne(idImage)
      .then(function (resp) {
        if (resp && resp.success) {
          state.done += 1;
        } else {
          state.failed.push({
            id_image: idImage,
            error: (resp && resp.error) ? resp.error : 'Unknown error'
          });
          state.done += 1;
        }
        return processQueue(state);
      })
      .catch(function (xhr) {
        var msg = 'Request failed';
        if (xhr && xhr.responseText) {
          msg = xhr.responseText;
        }
        state.failed.push({
          id_image: idImage,
          error: msg
        });
        state.done += 1;
        return processQueue(state);
      });
  }

  $(document).ready(function () {
    if (!window.rmbgpro || !window.rmbgpro.ajaxUrl) {
      return;
    }

    $('#rmbgpro-remove-bg').on('click', function () {
      var ids = getSelectedImageIds();
      if (!ids.length) {
        showMessage('error', 'Please select at least one image.');
        return;
      }

      setLoading(true);

      var state = {
        queue: ids.slice(0),
        total: ids.length,
        done: 0,
        failed: []
      };

      processQueue(state)
        .then(function (finalState) {
          if (finalState.failed.length) {
            showMessage('error', 'Done with errors. Failed: ' + finalState.failed.length + '/' + finalState.total + '. Reloading...');
          } else {
            showMessage('success', 'Done. Reloading...');
          }
          window.location.reload();
        })
        .always(function () {
          setLoading(false);
        });
    });

    setLoading(false);
  });
})();
