﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using GroceryCoKiosk.Groceries;

namespace GroceryCoKiosk.Discounts
{
    /// <summary>
    /// Represents a discount that applies for single items. IE: Apple on sale for $2.00.
    /// </summary>
    [Serializable]
    public class SingleItemDiscount : Discount
    {
        /// <summary>
        /// Creates a single item discount.
        /// </summary>
        public SingleItemDiscount()
        {
        }


        /// <summary>
        /// Creates a single item discount.
        /// </summary>
        /// <param name="groceryName">The name of the grocery being discounted.</param>
        /// <param name="discountPrice">The discount price for the sale.</param>
        /// <param name="discountName">The name of the discount to display to the user.</param>
        public SingleItemDiscount(string groceryName, decimal discountPrice, string discountName)
        {
            GroceryName = groceryName;
            DiscountName = discountName;
            DiscountPrice = discountPrice;
        }

        /// <summary>
        /// The default discount name to use if one is not provided
        /// </summary>
        protected override string DefaultDiscountName => $"{GroceryName} for {DiscountPrice:C}";

        /// <summary>
        /// The sale price.
        /// </summary>
        [Range(typeof(Decimal), "0.01", "1000000000000")]
        public decimal DiscountPrice { get; set; }

        /// <summary>
        /// Applies the discount. Any item that matches the GroceryName is sold for the discounted price.
        /// </summary>
        /// <param name="groceries">The list of groceries to apply the discount to.</param>
        public override void ApplyDiscountPrices(IEnumerable<GroceryPurchase> groceries)
        {
            var matchingGroceries = groceries.Where(item => item.Name == GroceryName).ToList();
            foreach (var purchase in matchingGroceries)
            {
                purchase.DiscountPrice = DiscountPrice;
                purchase.SalesNote = DiscountName;
            }
        }
    }
}