import state,{on}from"./store";import{setProduct}from"./setters";import{getVariantFromValues}from"../../functions/util";import{isStockNeedsToBeChecked}from"./getters";import{speak}from"@wordpress/a11y";import{__,sprintf}from"@wordpress/i18n";on("set",((e,t,i)=>{var a,d,o,l;(null===(a=null==t?void 0:t.selectedPrice)||void 0===a?void 0:a.id)!==(null===(d=null==i?void 0:i.selectedPrice)||void 0===d?void 0:d.id)&&updateSelectedPrice(e,t),(null===(o=null==t?void 0:t.selectedVariant)||void 0===o?void 0:o.id)!==(null===(l=null==i?void 0:i.selectedVariant)||void 0===l?void 0:l.id)&&handleStockWithSelectedVariant(e),(!i||["selectedPrice","adHocAmount","quantity","selectedVariant"].some((e=>JSON.stringify(t[e])!==JSON.stringify(i[e]))))&&setLineItem(e),(!i||JSON.stringify(null==t?void 0:t.variantValues)!==JSON.stringify(null==i?void 0:i.variantValues))&&updateSelectedVariant(e,t)}));const updateSelectedVariant=(e,t)=>{const i=getVariantFromValues({variants:state[e].variants,values:null==t?void 0:t.variantValues});i&&setProduct(e,{selectedVariant:i})},handleStockWithSelectedVariant=e=>{var t,i,a;state[e].selectedVariant&&isStockNeedsToBeChecked&&(null===(t=state[e])||void 0===t?void 0:t.selectedVariant.available_stock)<(null===(i=state[e])||void 0===i?void 0:i.quantity)&&(state[e].quantity=(null===(a=state[e])||void 0===a?void 0:a.selectedVariant.available_stock)||1,speak(sprintf(__("There are just %d items left in stock, and the quantity has been adjusted to %d.","surecart"),state[e].quantity,state[e].quantity),"assertive"))},updateSelectedPrice=(e,t)=>{var i,a,d,o;setProduct(e,{total:state[e].adHocAmount||(null===(i=null==t?void 0:t.selectedPrice)||void 0===i?void 0:i.amount)||0,adHocAmount:null===(a=null==t?void 0:t.selectedPrice)||void 0===a?void 0:a.amount,disabled:(null===(d=null==t?void 0:t.selectedPrice)||void 0===d?void 0:d.archived)||(null===(o=state[e].product)||void 0===o?void 0:o.archived)})},setLineItem=e=>{var t,i,a,d,o,l,n,s;setProduct(e,{line_item:{price_id:null===(i=null===(t=state[e])||void 0===t?void 0:t.selectedPrice)||void 0===i?void 0:i.id,quantity:Math.max((null===(d=null===(a=state[e])||void 0===a?void 0:a.selectedPrice)||void 0===d?void 0:d.ad_hoc)?1:state[e].quantity,1),...(null===(l=null===(o=state[e])||void 0===o?void 0:o.selectedPrice)||void 0===l?void 0:l.ad_hoc)?{ad_hoc_amount:null===(n=state[e])||void 0===n?void 0:n.adHocAmount}:{},variant:null===(s=state[e].selectedVariant)||void 0===s?void 0:s.id}})};