%% ------------------------------------
%% module       :tarot_log_mgr.erl
%% desc         :塔罗牌日志
%% author       :hh
%% time         :20/11/04
%% ------------------------------------

-module (tarot_log_mgr).

-behaviour (gen_server).

-export ([
    start_link/0
    ,add_tarot_log/4
    ,get_tarot_log/2
    ]).

-export ([
    init/1,
    handle_call/3,
    handle_cast/2,
    handle_info/2,
    terminate/2,
    code_change/3
    ]).

-include ("errcode.hrl").
-include("common.hrl").

-define (TAROT_LOG_LIST, 30).

-record (tarot_log, {
    role_id = 0,
    role_name = <<>>,
    goods_type = 0,
    goods_id = 0,
    goods_num = 0
    }).

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

add_tarot_log(SubType, RoleId, RoleName, GoodsList) ->
    gen_server:cast(?MODULE, {add_tarot_log, SubType, RoleId, RoleName, GoodsList}).

get_tarot_log(Sid, SubType) ->
    gen_server:cast(?MODULE, {get_tarot_log, SubType, Sid}).


init([]) ->
    {ok, []}.

handle_call(_Msg, _From, State) ->
    {reply, ok, State}.

handle_cast({add_tarot_log, SubType, RoleId, RoleName, GoodsList}, State) ->
    [{GoodsType, GoodsId, GoodsNum}|_] = GoodsList,
    NewLog = #tarot_log{
        role_id = RoleId, role_name = RoleName,
        goods_type = GoodsType, goods_id = GoodsId, goods_num = GoodsNum
    },
    NewState =
    case lists:keyfind(SubType, 1, State) of
        {_, TypeLogList} ->
            NewTypeLogList = [NewLog|TypeLogList],
            NewLen = length(NewTypeLogList),
            if NewLen > ?TAROT_LOG_LIST ->
                    NewTypeLogList1 = lists:sublist(NewTypeLogList, ?TAROT_LOG_LIST);
                true ->
                    NewTypeLogList1 = NewTypeLogList
            end,
            lists:keystore(SubType, 1, State, {SubType, NewTypeLogList1});
        _ ->
            lists:keystore(SubType, 1, State, {SubType, [NewLog]})
    end,
    {noreply, NewState};

handle_cast({get_tarot_log, SubType, Sid}, State) ->
    case lists:keyfind(SubType, 1, State) of
        {_, TypeLogList} ->
            TypeLogInfoList = pack_tarot_log_info(TypeLogList),
            lib_server_send:send_to_sid(Sid, pt_332, 33258, [?SUCCESS, SubType, TypeLogInfoList]);
        _ ->
            lib_server_send:send_to_sid(Sid, pt_332, 33258, [?SUCCESS, SubType, []])           
    end,
    {noreply, State};

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Msg, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

pack_tarot_log_info(LogList) ->
    [{GoodsType, GoodsId, GoodsNum, RoleName} || #tarot_log{
        role_name = RoleName, goods_type = GoodsType, goods_id = GoodsId, goods_num = GoodsNum} <- LogList].