import * as React from "react";
import { DeliveryType, IDeliveryType, IPaymentType, IShoppingCartItem } from "../../../../apiModels/ViewModels";

type OrderSummaryProps = {
	orderItems: IShoppingCartItem[],
	deliveryType: IDeliveryType,
	paymentType: IPaymentType
}

class OrderSummary extends React.Component<OrderSummaryProps> {
	calculateProductsPrice = (): number => {
		return this.props.orderItems.reduce(function (sum: number, obj: IShoppingCartItem) { return sum + (obj.price * obj.amount); }, 0);
	}

	calculateTotalPrice = (productPrice: number): number => {
		let totalPrice: number = 0;
		this.props.orderItems.forEach(item => {
			totalPrice += (Math.round(((item.price * item.amount) + Number.EPSILON) * 100) / 100)
		})

		totalPrice += this.props.deliveryType.fee;
		totalPrice += this.props.paymentType.fee;

		return productPrice >= 1000 ? totalPrice - this.props.deliveryType.fee : totalPrice;
	}

	render() {
		const { orderItems, deliveryType, paymentType } = this.props;
		let productPrice = this.calculateProductsPrice();
		let totalPrice = this.calculateTotalPrice(productPrice);

		return (
			<React.Fragment>
				<h4>Vaše objednávka</h4>
				<div className="checkout__order__products">Produkty <span>Cena</span></div>
				<ul>
					{orderItems.map((item: IShoppingCartItem) => {
						return <li key={item.productID}>
							{item.name}
							<span>
								{(item.price * item.amount).toFixed(2)} Kč
							</span>
						</li>
					})}
				</ul>
				<div className="checkout__order__subtotal">
					Produkty celkem <span>{productPrice.toFixed(2)} Kc</span>
				</div>
				<ul>
					{deliveryType !== undefined && deliveryType.id !== 0
						? <li>{deliveryType.name} <span>+ {deliveryType.fee} Kč</span></li>
						: ''
					}
					{deliveryType.id == DeliveryType.Delivery && productPrice >= 1000
						? <li>{deliveryType.name} (SLEVA)<span>- {deliveryType.fee} Kč</span></li>
						: null}
					{deliveryType !== undefined && paymentType !== undefined && deliveryType.id !== 0 && paymentType.id !== 0
						? <li>{paymentType.name} <span>+ {paymentType.fee} Kč</span></li>
						: ''
					}
				</ul>
				<div className="checkout__order__total">Cena celkem <span>{Math.round(totalPrice)} Kč</span></div>
			</React.Fragment>
		);
	}
}

export default OrderSummary;