/**
 * RMBG PRO - Products list page (products-v2) bulk action
 */

(function () {
  function ensureBulkActionItem($menu) {
    if (!$menu || !$menu.length) {
      return;
    }
    if ($menu.find('#rmbgpro-bulk-remove-bg-products').length) {
      return;
    }

    var disabledAttr = (window.rmbgproProductsList && window.rmbgproProductsList.enabled)
      ? ''
      : 'disabled="disabled" aria-disabled="true"';

    $menu.append(
      '<div class="dropdown-divider"></div>' +
      '<a href="#" class="dropdown-item" id="rmbgpro-bulk-remove-bg-products" ' + disabledAttr + '>' +
      'Remove backgrounds (all images of selected products)' +
      '</a>'
    );
  }

  function getSelectedProductIds() {
    var ids = {};
    $('table input[type="checkbox"]:checked').each(function () {
      var v = $(this).val();
      if (typeof v === 'string' && /^[0-9]+$/.test(v)) {
        ids[v] = true;
      }
    });
    return Object.keys(ids).map(function (v) { return parseInt(v, 10); });
  }

  function showMessage(type, message) {
    if (typeof showSuccessMessage === 'function' && type === 'success') {
      showSuccessMessage(message);
      return;
    }
    if (typeof showErrorMessage === 'function' && type === 'error') {
      showErrorMessage(message);
      return;
    }
    alert(message);
  }

  function processBatch(productIds) {
    return $.ajax({
      url: window.rmbgproProductsList.ajaxUrl,
      method: 'POST',
      dataType: 'json',
      data: {
        ajax: 1,
        action: 'bulkRemoveBackgroundProducts',
        product_ids: productIds
      }
    });
  }

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

    $(document).on('shown.bs.dropdown', function (e) {
      var $dropdown = $(e.target);
      var $menu = $dropdown.find('.dropdown-menu');
      ensureBulkActionItem($menu);
    });

    setTimeout(function () {
      ensureBulkActionItem($('.dropdown-menu.show'));
    }, 0);

    $(document).on('click', '#rmbgpro-bulk-remove-bg-products', function (e) {
      e.preventDefault();

      if (!window.rmbgproProductsList.enabled) {
        showMessage('error', 'RMBG PRO API key is missing. Configure the module first.');
        return;
      }

      var ids = getSelectedProductIds();
      if (!ids.length) {
        showMessage('error', 'Please select at least one product.');
        return;
      }

      var chunkSize = 5;
      var queue = ids.slice(0);
      var processed = 0;
      var failed = [];

      function step() {
        if (!queue.length) {
          if (failed.length) {
            showMessage('error', 'Done with errors. Failed: ' + failed.length + '/' + ids.length);
          } else {
            showMessage('success', 'Done. Processed: ' + processed);
          }
          window.location.reload();
          return;
        }

        var batch = queue.splice(0, chunkSize);
        showMessage('success', 'Processing... (' + processed + '/' + ids.length + ')');

        processBatch(batch)
          .done(function (resp) {
            if (!resp || !resp.success) {
              batch.forEach(function (pid) {
                failed.push({ id_product: pid, error: (resp && resp.error) ? resp.error : 'Unknown error' });
              });
              processed += batch.length;
            } else {
              processed += resp.processed || 0;
              if (resp.failed && resp.failed.length) {
                resp.failed.forEach(function (f) { failed.push(f); });
              }
            }
            step();
          })
          .fail(function (xhr) {
            var msg = 'Request failed';
            if (xhr && xhr.responseText) {
              msg = xhr.responseText;
            }
            batch.forEach(function (pid) {
              failed.push({ id_product: pid, error: msg });
            });
            processed += batch.length;
            step();
          });
      }

      step();
    });
  });
})();
