/*
 * This File is one of the examples from Java Application Development
 * Do not reproduce this code for others or use it in a commercial setting without prior permission from the author.
 */

package salesApplication;

import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import products.Item;

/**
 *
 * @author Matthew Gregory
 * @website www.matthewgregory-author.com.au
 *
 */
public class Search {
    //This class allows us to search our price lists for items where fields such as name
    //and decsription match a specified search criteria.

    //Given a price list, search for all items where something in the description or name matches 
    //the search string
    public static PriceList searchList(PriceList priceList,String pattern){
        //Simple search for string in name or description
        
        //Create the search functionality and save it in a lambda expression
        Predicate<Item> searchFunctionality = (item)->{
//            System.out.println("Searching for pattern: "+pattern+" In item "+item.getName()+": "+item.getDescription());
            Pattern p = Pattern.compile(pattern);
            Matcher nameMatch = p.matcher(item.getName());
            Matcher descriptionMatch = p.matcher(item.getDescription());
//            return nameMatch.find()||descriptionMatch.find();
            return nameMatch.matches()||descriptionMatch.matches();
//            return item.getName().matches(pattern)||item.getDescription().matches(pattern); 
        };
        
        //Use the lambda expression to filter the list.
        return priceList.filterList(searchFunctionality);
    }
    
}
