-module(fruit_shop).
-export([spawn_shop/2, spawn_shop/3, buy/2, stock/1]).

buy( FruitShop, Order ) ->
FruitShop ! { self(), buy, Order },
receive
{ FruitShop, purchased, Price } -> {purchased, Price};
{ FruitShop, out_of_stock } -> out_of_stock
after 10000 ->
timeout
end.

stock( FruitShop ) ->
FruitShop ! { self(), stock },
receive
{ FruitShop, stock, Stock } -> Stock
after 10000 ->
timeout
end.

spawn_shop( Node, Stock, Prices ) ->
spawn(
Node,
fun() ->
fruit_shop_loop( Stock, Prices )
end
).

spawn_shop( Stock, Prices ) ->
spawn(
fun() ->
fruit_shop_loop( Stock, Prices )
end
).

fruit_shop_loop( Stock, Prices ) ->
receive
{Buyer, stock} ->
Buyer ! {self(), stock, Stock},
fruit_shop_loop( Stock, Prices );
{Buyer, buy, Order} ->
{NewStock, Price} = buy( Order, Stock, Prices ),
case Price of
out_of_stock ->
Buyer ! {self(), out_of_stock},
fruit_shop_loop( Stock, Prices );
_ ->
Buyer ! {self(), purchased, Price},
fruit_shop_loop( NewStock, Prices )
end
end.

buy( Order, Stock, Prices ) -> buy( Order, Stock, Prices, 0.0 ).

buy( [], Stock, _Prices, Acum ) ->
{Stock, Acum};

buy( [{Kilos, Fruit} | Rest], Stock, Prices, Acum ) ->
FruitStock = proplists:get_value(Fruit, Stock, 0.0),
Stocked = Kilos =< FruitStock,
case Stocked of
true ->
Price = proplists:get_value(Fruit, Prices),
NewStock = [ {Fruit, FruitStock - Kilos}, proplists:delete(Fruit, Stock) ],
buy( Rest, NewStock, Prices, Acum + (Price * Kilos));
false -> {keep_old_stock, out_of_stock}
end.