-module(pt_420).
-include("common.hrl").
-export([
        read/2,
        write/2
    ]).

read(42001, _) ->
    {ok, []};
read(42002, Bin0) ->
    <<Type:8, _Bin1/binary>> = Bin0, 
    {ok, [Type]};
read(42003, Bin0) ->
    <<Type:8, Bin1/binary>> = Bin0, 
    <<Id:8, _Bin2/binary>> = Bin1, 
    {ok, [Type, Id]};
read(_Cmd, _R) -> {error, no_match}.

write (42000,[
    Code,
    Args
] = Src_Data) ->
    Bin_Args = pt:write_string(Args), 

    Data = <<
        Code:32,
        Bin_Args/binary
    >>,
    {ok, pt:encode(42000, Data, Src_Data)};

write (42001,[
    List
] = Src_Data) ->
    BinList_List = [
        item_to_bin_0(List_Item) || List_Item <- List
    ], 

    List_Len = length(List), 
    Bin_List = list_to_binary(BinList_List),

    Data = <<
        List_Len:16, Bin_List/binary
    >>,
    {ok, pt:encode(42001, Data, Src_Data)};

write (42002,[
    Res
] = Src_Data) ->
    Data = <<
        Res:32
    >>,
    {ok, pt:encode(42002, Data, Src_Data)};

write (42003,[
    Type,
    Id
] = Src_Data) ->
    Data = <<
        Type:8,
        Id:8
    >>,
    {ok, pt:encode(42003, Data, Src_Data)};

write(_Cmd, _R) -> ?DEBUG("no_match:~p,~p~n", [_Cmd, _R]), {ok, pt:pack(0, <<>>)}.


item_to_bin_0 ({
    Type,
    Round,
    IsBuy,
    BuyTime,
    Rewards
}) ->
    BinList_Rewards = [
        item_to_bin_1(Rewards_Item) || Rewards_Item <- Rewards
    ], 

    Rewards_Len = length(Rewards), 
    Bin_Rewards = list_to_binary(BinList_Rewards),

    Data = <<
        Type:8,
        Round:8,
        IsBuy:8,
        BuyTime:32,
        Rewards_Len:16, Bin_Rewards/binary
    >>,
    Data.
item_to_bin_1 (
    Id
) ->
    Data = <<
        Id:8
    >>,
    Data.
