( function ($) {

  const quixRefund = {
    init: function () {
      this.config()
    },
    config: function () {
      this.$buttonApiRefund  = $('.wc-order-refund-items .do-api-refund')
      this.$buttonQuixRefund = $('<button class="button button-primary do-quix-refund">'+addonpayments.button_text+'</button>')

      this.$buttonApiRefund.remove()
      this.$buttonQuixRefund.insertBefore('.wc-order-refund-items .do-manual-refund')

      this.$buttonQuixRefund.on('click', this.renderWidget.bind(this))
    },
    renderWidget: function (e) {
      e.preventDefault();
      $( 'body' ).css( 'cursor', 'progress' );
      const that = this;
      let ajaxExecutor = new XMLHttpRequest()

      ajaxExecutor.onreadystatechange = function () {
        if (ajaxExecutor.readyState !== 4) return;
        if (ajaxExecutor.status >= 200 && ajaxExecutor.status < 300) {

          try {
            const response = JSON.parse(ajaxExecutor.response)

            if(!response.success) {
              $message = addonpayments.error_message;

              if(response.data.error) {
                $message += ': ' + response.data.error;
              }

              alert($message)
              return;
            }

            NEMURUORDERMANAGEMENT.setEpgBaseUrl(addonpayments.base_url);
            NEMURUORDERMANAGEMENT.renderOrderManagementWidget(response.data, 'epgjs-cashier-div',
              that.closeCallback,
              that.errorCallback,
              that.successCallback
            );

          }
          catch (error) {
            console.log(error)
          }
        }
      }

      const data = {
        'order_id': addonpayments.order_id,
        'nonce': addonpayments.nonce
      }

      ajaxExecutor.open('POST', addonpayments.url + '?action=' + addonpayments.action)
      ajaxExecutor.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
      ajaxExecutor.send( new URLSearchParams(data).toString() )

    },
    successCallback: function (action) {
    },
    errorCallback: function (action) {
    },
    closeCallback: function (action) {
      window.location.replace(addonpayments.callback)
    }
  }

  document.addEventListener('DOMContentLoaded', function () {
    if ($('.refund-actions button.do-api-refund').length > 0
      && ( addonpayments.payment_solution === 'quix' || addonpayments.payment_solution === 'nemuru' )) {
      quixRefund.init()
    }
  })

} )(jQuery)
