/**
 * RMBG PRO - Module configuration JS (bulk processing)
 */

(function () {
  function appendLog(html) {
    var $log = $('#rmbgpro-bulk-log');
    $log.append('<div>' + html + '</div>');
  }

  function setStatus(text, isOk) {
    var $status = $('#rmbgpro-api-status');
    if (!$status.length) {
      return;
    }
    $status.text(text);
    $status.css('color', isOk === true ? '#2e7d32' : (isOk === false ? '#c62828' : ''));
  }

  function setValidateLoading(isLoading) {
    $('#rmbgpro-validate-spinner').toggle(isLoading);
    $('#rmbgpro-validate-key').prop('disabled', isLoading || !(window.rmbgproStatus && window.rmbgproStatus.enabled));
  }

  function setLoading(isLoading) {
    $('#rmbgpro-bulk-spinner').toggle(isLoading);
    $('#rmbgpro-bulk-start').prop('disabled', isLoading || !(window.rmbgproBulk && window.rmbgproBulk.enabled));
  }

  function processBatch(state) {
    return $.ajax({
      url: window.rmbgproBulk.ajaxUrl,
      method: 'POST',
      dataType: 'json',
      data: {
        ajax: 1,
        action: 'bulkRemoveBackground',
        last_id: state.lastId,
        limit: state.limit
      }
    }).then(function (resp) {
      if (!resp || !resp.success) {
        throw new Error((resp && resp.error) ? resp.error : 'Unknown error');
      }

      state.lastId = resp.last_id || state.lastId;
      state.processed += resp.processed || 0;
      state.failed = state.failed.concat(resp.failed || []);

      appendLog('Processed: ' + state.processed + (resp.processed ? (' (+' + resp.processed + ')') : ''));

      if (resp.failed && resp.failed.length) {
        appendLog('Failed in batch: ' + resp.failed.length);
      }

      if (resp.has_more) {
        return processBatch(state);
      }

      return state;
    });
  }

  $(document).ready(function () {
    if (window.rmbgproStatus && window.rmbgproStatus.ajaxUrl) {
      $('#rmbgpro-validate-key').on('click', function () {
        setValidateLoading(true);
        setStatus('Checking...', null);

        $.ajax({
          url: window.rmbgproStatus.ajaxUrl,
          method: 'POST',
          dataType: 'json',
          data: {
            ajax: 1,
            action: 'validateKey'
          }
        })
          .done(function (resp) {
            if (resp && resp.success) {
              setStatus(resp.message || 'API key is valid', true);
              return;
            }
            setStatus((resp && resp.error) ? resp.error : 'Invalid API key', false);
          })
          .fail(function () {
            setStatus('Validation request failed', false);
          })
          .always(function () {
            setValidateLoading(false);
          });
      });

      setValidateLoading(false);
    }

    if (!window.rmbgproBulk || !window.rmbgproBulk.ajaxUrl) {
      return;
    }

    $('#rmbgpro-bulk-start').on('click', function () {
      setLoading(true);
      $('#rmbgpro-bulk-log').empty();
      appendLog('Starting bulk processing...');

      var state = {
        lastId: 0,
        limit: 10,
        processed: 0,
        failed: []
      };

      processBatch(state)
        .then(function (finalState) {
          appendLog('Done. Total processed: ' + finalState.processed);
          if (finalState.failed.length) {
            appendLog('Total failed: ' + finalState.failed.length);
          }
        })
        .catch(function (err) {
          appendLog('Error: ' + (err && err.message ? err.message : String(err)));
        })
        .always(function () {
          setLoading(false);
        });
    });

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