import { Component, Element, Event, h, Listen, Prop, State, Watch } from '@stencil/core';
import { updateCheckout } from '../../../services/session';
export class ScCartSessionProvider {
  /** Sync this session back to parent. */
  handleSessionUpdate(val) {
    this.scUpdateOrderState.emit(val);
  }
  handleUpdateSession(e) {
    const { data, options } = e.detail;
    if (options === null || options === void 0 ? void 0 : options.silent) {
      this.update(data);
    }
    else {
      this.loadUpdate(data);
    }
  }
  /** Handles coupon updates. */
  async handleCouponApply(e) {
    const promotion_code = e.detail;
    this.scError.emit({});
    this.loadUpdate({
      discount: {
        ...(promotion_code ? { promotion_code } : {}),
      },
    });
  }
  /** Handle the error response. */
  handleErrorResponse(e) {
    if ((e === null || e === void 0 ? void 0 : e.code) === 'readonly') {
      this.scUpdateOrderState.emit(null);
    }
    // expired
    if ((e === null || e === void 0 ? void 0 : e.code) === 'rest_cookie_invalid_nonce') {
      this.scSetState.emit('idle');
      return;
    }
    // something went wrong
    if (e === null || e === void 0 ? void 0 : e.message) {
      this.scError.emit(e);
    }
    // handle curl timeout errors.
    if ((e === null || e === void 0 ? void 0 : e.code) === 'http_request_failed') {
      this.scError.emit({ message: 'Something went wrong. Please reload the page and try again.' });
    }
    this.scSetState.emit('idle');
  }
  /** Fetch a session. */
  async fetch(args = {}) {
    this.loadUpdate({ status: 'draft', ...args });
  }
  /** Update a the order */
  async update(data = {}, query = {}) {
    var _a;
    try {
      this.session = (await updateCheckout({
        id: (_a = this.order) === null || _a === void 0 ? void 0 : _a.id,
        data: {
          ...data,
        },
        query: {
          ...query,
        },
      }));
    }
    catch (e) {
      console.error(e);
      throw e;
    }
  }
  /** Updates a session with loading status changes. */
  async loadUpdate(data = {}) {
    try {
      this.scSetState.emit('busy');
      await this.update(data);
      this.scSetState.emit('idle');
    }
    catch (e) {
      this.handleErrorResponse(e);
    }
  }
  render() {
    return (h("sc-line-items-provider", { order: this.order, onScUpdateLineItems: e => this.loadUpdate({ line_items: e.detail }) },
      h("slot", null)));
  }
  static get is() { return "sc-cart-session-provider"; }
  static get encapsulation() { return "shadow"; }
  static get properties() { return {
    "order": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Checkout",
        "resolved": "Checkout",
        "references": {
          "Checkout": {
            "location": "import",
            "path": "../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Order Object"
      }
    }
  }; }
  static get states() { return {
    "session": {}
  }; }
  static get events() { return [{
      "method": "scUpdateOrderState",
      "name": "scUpdateOrderState",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Update line items event"
      },
      "complexType": {
        "original": "Checkout",
        "resolved": "Checkout",
        "references": {
          "Checkout": {
            "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": {}
      }
    }, {
      "method": "scSetState",
      "name": "scSetState",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Set the state"
      },
      "complexType": {
        "original": "'loading' | 'busy' | 'navigating' | 'idle'",
        "resolved": "\"busy\" | \"idle\" | \"loading\" | \"navigating\"",
        "references": {}
      }
    }]; }
  static get elementRef() { return "el"; }
  static get watchers() { return [{
      "propName": "session",
      "methodName": "handleSessionUpdate"
    }]; }
  static get listeners() { return [{
      "name": "scUpdateOrder",
      "method": "handleUpdateSession",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "scApplyCoupon",
      "method": "handleCouponApply",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
