package com.pnehls;

import java.util.ArrayList;

//Shopping Cart acts as the Originator in this pattern
public class ShoppingCart {
	
	//state which will be saved in memento
	private ArrayList<String> contents = new ArrayList<String>();
	
	//constructor
	public ShoppingCart(){
		
	}
	
	//addItem and removeItem effectively act as setState() from the pattern UML
	public void addItem(String s){
		contents.add(s);
		
		System.out.println(s + " added to Shopping Cart.\n");
	}
	
	public void removeItem(String s){
		contents.remove(s);
		System.out.println(s + " removed to Shopping Cart.\n");

	}
	
	//printContents acts as getState() from the pattern
	public void printContents(){
		
		String s = "Shopping Cart contains: ";
		
		for (String item : contents){
			s += item + ", ";
		}
		//remove last comma
		
		if (s.endsWith(": ")){
			s = "Shopping Cart is empty!";
		}
		else {
			s = s.substring(0, s.length()-2) + ".";
		}
		
		System.out.println(s + "\n");
	}
	
	//creates a memento with the contents of the shopping cart
	public Memento saveStateToMemento(){
		System.out.println("Saving State to Memento\n");
		Memento m = new Memento(contents);
		return m;
	}
	
	//loads the shopping cart contents from a memento passed to Originator
	public void getStateFromMemento(Memento m){
		System.out.println("reloading saved state from memento\n");
		contents.clear();
		for (String s : m.getState()){
			contents.add(s);
		}
	}
	

}
