import{h,Host}from"@stencil/core";import{state as checkoutState,onChange as onCheckoutChange}from"../../../store/checkout/index";import{lockCheckout,unLockCheckout}from"../../../store/checkout/mutations";import{state as userState,onChange as onUserChange}from"../../../store/user/index";import{createOrUpdateCheckout}from"../../../services/session";import{getCurrentCustomer,hasAddressData,isAddressEmpty}from"../../../services/customer-address";export class ScCheckoutAutofillProvider{componentWillLoad(){this.maybeApplyProfile(),this.removeUserListener=onUserChange("loggedIn",(e=>{e?this.maybeApplyProfile():this.appliedForCheckoutId=void 0})),this.removeCheckoutListener=onCheckoutChange("checkout",(()=>this.maybeApplyProfile()))}disconnectedCallback(){var e,t;null===(e=this.removeUserListener)||void 0===e||e.call(this),null===(t=this.removeCheckoutListener)||void 0===t||t.call(this)}async maybeApplyProfile(){var e,t,o,i,s,c,a,r;if(!userState.loggedIn)return;const l=null===(e=checkoutState.checkout)||void 0===e?void 0:e.id;if(l&&this.appliedForCheckoutId!==l){this.appliedForCheckoutId=l;try{const e=await getCurrentCustomer(checkoutState.mode),l={},n=null==e?void 0:e.shipping_address,h=null==e?void 0:e.billing_address;if(hasAddressData(n)&&isAddressEmpty(null===(t=checkoutState.checkout)||void 0===t?void 0:t.shipping_address)&&(l.shipping_address=n),hasAddressData(h)&&isAddressEmpty(null===(o=checkoutState.checkout)||void 0===o?void 0:o.billing_address)&&(l.billing_address=h),(null==e?void 0:e.first_name)&&!(null===(i=checkoutState.checkout)||void 0===i?void 0:i.first_name)&&(l.first_name=e.first_name),(null==e?void 0:e.last_name)&&!(null===(s=checkoutState.checkout)||void 0===s?void 0:s.last_name)&&(l.last_name=e.last_name),(null==e?void 0:e.phone)&&!(null===(c=checkoutState.checkout)||void 0===c?void 0:c.phone)&&(l.phone=e.phone),"boolean"==typeof(null==e?void 0:e.billing_matches_shipping)&&(null===(a=checkoutState.checkout)||void 0===a?void 0:a.billing_matches_shipping)!==e.billing_matches_shipping&&(l.billing_matches_shipping=e.billing_matches_shipping),!Object.keys(l).length)return;lockCheckout("customer-profile-autofill");try{checkoutState.checkout=await createOrUpdateCheckout({id:null===(r=checkoutState.checkout)||void 0===r?void 0:r.id,data:l})}finally{unLockCheckout("customer-profile-autofill")}}catch(e){this.appliedForCheckoutId=void 0,console.error(e)}}}render(){return h(Host,{key:"7b4a4103b672ec8cc8418f63f50590a9f97f581b"},h("slot",{key:"44495fa4b9fc3b0722a2f1c3fd707fa356a7b59d"}))}static get is(){return"sc-checkout-autofill-provider"}static get encapsulation(){return"shadow"}}