/*
 * This File is one of the examples from Java Object Oriented Programming
 * Do not reproduce this code for others or use it in a commercial setting without prior permission from the author.
 */
package salesApplication;

import products.Item;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import static salesApplication.CompanyInfo.COPYRIGHT_NOTICE;

/**
 *
 * @author Matthew Gregory
 * @website www.matthewgregory-author.com.au
 *
 */

public class PriceList {

    //A collection of products that belong on our price list.
    public List<Item> list = new ArrayList<>();
    final LocalDate DATE_CREATED;
    
    public PriceList(){
        DATE_CREATED = LocalDate.now();
    }

    public List<Item> getList() {
        return list;
    }

    //Adds a product to our price list (provided their is no other product with that name).
    public void addProduct(Item newItem) {
        boolean exists=false;
        //If a product with this name already exists print out a message and stop.
        for (Item p : list) {
            if (p.equals(newItem)) {
                System.out.println("A product already exists with that name.");
                exists=true;
            }
        }
        if (!exists) {
            list.add(newItem);
        } else {}
    }

    //Removes a product on our price list based on the name of the product.
    public void removeProduct(String productName) {
        for (Item p : list) {
            if (p.getName().equals(productName)) {
                list.remove(p);
                return;
            }
        }
    }

    public void printList() {
        //Print out the price list
        System.out.println("== Price list (current as of " + DATE_CREATED + ") ==");

        //For each product in our list, print out the product details
        for (Item p : list) {
            //Put a blank line between each product
            System.out.println();
            //Get the product to print out the details
            p.printProduct();
        }
        System.out.println("== End of Price List ==");
        System.out.println();
        System.out.println(COPYRIGHT_NOTICE);
    }
    
    //Return a filtered price list. Lambda version with generics to specify type
    public PriceList filterList(Predicate<Item> filter){
        PriceList filteredList = new PriceList();
        for (Item i:this.getList()){
            if (filter.test(i)){
                filteredList.addProduct(i);
            }
        }
        return filteredList;
    }
    
    //Return a price list after applying the discount defined by the lambda calcuation.
    public PriceList applyDiscount(UnaryOperator<Item> calculation){
        PriceList modifiedList = new PriceList();
        for (Item i:this.getList()){
                modifiedList.addProduct(calculation.apply(i));
            }
        return modifiedList;
    }
    
}
