%% ---------------------------------------------------------
%% Author:  xyj
%% Email:   156702030@qq.com
%% Created: 2011-12-23
%% Description: 物品进程字典
%% --------------------------------------------------------
-module(lib_goods_dict).
-compile(export_all).
-include("goods.hrl").
-include("sell.hrl").
-include("common.hrl").
-include("server.hrl").
-define(GOODS_ACT, {?MODULE, goods_act}).

%% 进程字典
start_dict() ->
	put(?GOODS_ACT, []),
	ok.

close_dict() ->
	erase(?GOODS_ACT),
	ok.

%% 过程中新增处理。一般是存起来，最后统一处理
append_dict(Val, Dict) ->
	case get(?GOODS_ACT) of
		undefined ->
			NewDict = handle_item([[Val]], Dict);
		Val2 ->
			put(?GOODS_ACT, Val2++[Val]),
            NewDict = Dict
	end,
	NewDict.

%% 物品处理结束。统一修改物品
handle_dict_and_notify(Dict) ->
    {NewDict, Value} = do_handle_dict(Dict),
    GoodsList = get_goods_list(Value, Dict, []),
    {NewDict, GoodsList}.

do_handle_dict(Dict) ->
    {NewDict, Value} = case erase(?GOODS_ACT) of
        undefined ->
            {Dict, []};
        Val when is_list(Val) ->
            NewD = handle_item([Val], Dict),
            {NewD, Val};
        _ ->
            {Dict, []}
    end,
    {NewDict, Value}.

handle_item([[]], D) ->
    D;
handle_item([Item], D) ->
    [Item1|T] = Item,
    D1 = handle_item1(Item1, D),
    handle_item([T], D1).

handle_item1(Item, D) ->
    case Item of
        {add, goods, GoodsInfo} ->
            D1 = add_dict_goods(GoodsInfo, D);
        {del, goods, GoodsInfo} ->
            D1 = del_dict_goods(GoodsInfo, D);
        _Other ->
            D1 = D
    end,
    D1.

%% 增加物品
add_dict_goods(GoodsInfo, GoodsMaps) ->
    Key = GoodsInfo#goods.id,
    Location = GoodsInfo#goods.location,
    case is_integer(Key) andalso Key > 0 of
        true ->
            LocationDict = lib_goods_util:get_location_goods(GoodsMaps, Location),
            LocationDict1 = dict:store(Key, GoodsInfo, LocationDict),
            lib_goods_util:put_location_goods(GoodsMaps, Location, LocationDict1);
        false ->
            GoodsMaps
    end.

%% 删除物品
del_dict_goods(GoodsInfo, GoodsMaps) ->
    Key = GoodsInfo#goods.id,
    Location = GoodsInfo#goods.location,
    LocationDict = lib_goods_util:get_location_goods(GoodsMaps, Location),
    LocationDict1 = dict:erase(Key, LocationDict),
    lib_goods_util:put_location_goods(GoodsMaps, Location, LocationDict1).

%% 获得所有修改的物品 增加的放后面/删除的放前面(后面的反过来的)
%% 为了保证发起前端的是 先删后增
get_goods_list([], _Dict, GoodsList) -> GoodsList;
get_goods_list([{Type, _, GoodsInfo} | T], Dict, GoodsList) ->
    case Type of
        add -> get_goods_list(T, Dict, GoodsList ++ [GoodsInfo]);
        del -> get_goods_list(T, Dict, [GoodsInfo | GoodsList])
    end.
%%----------------------------------------
%% 取出字典中的所有values
%%----------------------------------------
fetch_values(Dict) ->
    dict:fold(fun (_Key, Val, Values) -> [Val|Values] end, [], Dict).
