const osEl = {
  $discountList: $('.checkout-widget__details-discount ul'),
  discountItem: '.checkout-widget__details-discount',
}

export function updateDiscount(data, isVoucher) {
  if ((Array.isArray(data.promotionsInfo) && data.promotionsInfo.length)) {
    $(osEl.discountItem).show();
    osEl.$discountList.empty();

    !data.promotionsInfo || data.promotionsInfo.forEach(function (discountObj) {
      appendOrderPromotions(discountObj);
    });
  } else if (isVoucher && (Array.isArray(data.promotionsInfo) && data.promotionsInfo.length)) {
    $(osEl.discountItem).show();
    osEl.$discountList.empty();

    data.promotionsInfo.forEach(function (discountItem) {
      osEl.$discountList.append(function () {
        if (discountItem.usedCouponCode && discountItem.description) {
          return `
            <li data-coupon-code="${discountItem.usedCouponCode}">
              ${discountItem.description}
              <span class="icon checkout-widget__voucher-remove">
                <span class="fas fa-times"></span>
              </span>
            </li>
          `
        } else if (discountItem.description) {
          return `
            <li>${discountItem.description}</li>
          `
        } else {
          return ''
        }

      });
    });
  } else {
    $(osEl.discountItem).hide();
  }
}

function appendOrderPromotions(discountObj) {
  if (!_.isEmpty(discountObj)) {
    if (discountObj.usedCouponCode && discountObj.description) {
      osEl.$discountList.append(createRemoveCouponItem(discountObj));
    } else if (discountObj.description) {
      osEl.$discountList.append(function () {
        return `<li>${discountObj.description}</li>`
      });
    }
  }
}

function createRemoveCouponItem(obj) {
  return `
    <li data-coupon-code="${obj.usedCouponCode}">
      ${obj.description}
      <span class="icon checkout-widget__voucher-remove">
        <span class="fas fa-times"></span>
      </span>
    </li>
`
}
