import { Component, Element, Event, h, Listen, Prop } from '@stencil/core';
import { addQueryArgs } from '@wordpress/url';
import apiFetch from '../../../functions/fetch';
import { parseFormData } from '../../../functions/form-data';
import { expand } from '../../../services/session';
import { clearOrder } from '../../../store/checkouts';
/**
 * This component listens to the order status
 * and confirms the order when payment is successful.
 */
export class ScOrderConfirmProvider {
  constructor() {
    /** Are we in test or live mode. */
    this.mode = 'live';
  }
  /** Listen for paid event. This is triggered by Stripe or Paypal elements when payment succeeds. */
  handlePaidEvent() {
    this.confirmOrder();
  }
  /** Confirm the order. */
  async confirmOrder() {
    var _a, _b;
    const json = await this.el.querySelector('sc-form').getFormJson();
    let data = parseFormData(json);
    try {
      const confirmed = (await apiFetch({
        method: 'PATCH',
        path: addQueryArgs(`surecart/v1/checkouts/${(_a = this.order) === null || _a === void 0 ? void 0 : _a.id}/confirm`, [expand]),
        data,
      }));
      // emit the confirmed event to trigger listeners to redirect to the success url, etc.
      this.scConfirmed.emit();
      // emit the order paid event for tracking scripts.
      this.scOrderPaid.emit(confirmed);
    }
    catch (e) {
      console.error(e);
      this.scError.emit(e);
    }
    finally {
      const order = (_b = this.order) === null || _b === void 0 ? void 0 : _b.id;
      // make sure we clear the order state no matter what.
      clearOrder(this.formId, this.mode);
      // we always want to redirect, regardless of the outcome here.
      window.location.assign(addQueryArgs(this.successUrl, { order }));
    }
  }
  render() {
    return h("slot", null);
  }
  static get is() { return "sc-order-confirm-provider"; }
  static get encapsulation() { return "shadow"; }
  static get properties() { return {
    "formId": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The form id"
      },
      "attribute": "form-id",
      "reflect": false
    },
    "mode": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'test' | 'live'",
        "resolved": "\"live\" | \"test\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Are we in test or live mode."
      },
      "attribute": "mode",
      "reflect": false,
      "defaultValue": "'live'"
    },
    "order": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Order",
        "resolved": "Order",
        "references": {
          "Order": {
            "location": "import",
            "path": "../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The current order."
      }
    },
    "successUrl": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Success url."
      },
      "attribute": "success-url",
      "reflect": false
    }
  }; }
  static get events() { return [{
      "method": "scConfirmed",
      "name": "scConfirmed",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "The order is confirmed event."
      },
      "complexType": {
        "original": "void",
        "resolved": "void",
        "references": {}
      }
    }, {
      "method": "scOrderPaid",
      "name": "scOrderPaid",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "The order is paid event."
      },
      "complexType": {
        "original": "Order",
        "resolved": "Order",
        "references": {
          "Order": {
            "location": "import",
            "path": "../../../types"
          }
        }
      }
    }, {
      "method": "scError",
      "name": "scError",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Error event."
      },
      "complexType": {
        "original": "{ message: string; code?: string; data?: any; additional_errors?: any } | {}",
        "resolved": "{ message: string; code?: string; data?: any; additional_errors?: any; } | {}",
        "references": {}
      }
    }]; }
  static get elementRef() { return "el"; }
  static get listeners() { return [{
      "name": "scPaid",
      "method": "handlePaidEvent",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
