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

read(15301, Bin0) ->
    <<Type:8, _Bin1/binary>> = Bin0, 
    {ok, [Type]};
read(15302, Bin0) ->
    FunArray0 = fun(<<RestBin0/binary>>) -> 
        <<KeyId:32, _Args1/binary>> = RestBin0, 
        <<Num:32, _Args2/binary>> = _Args1, 
        {{KeyId, Num},_Args2}
        end,
    {KeyList, Bin1} = pt:read_array(FunArray0, Bin0),

    <<Type:8, _Bin2/binary>> = Bin1, 
    {ok, [KeyList, Type]};
read(15304, Bin0) ->
    <<GoodsId:32, Bin1/binary>> = Bin0, 
    <<Num:32, Bin2/binary>> = Bin1, 
    <<BuyType:8, _Bin3/binary>> = Bin2, 
    {ok, [GoodsId, Num, BuyType]};
read(_Cmd, _R) -> {error, no_match}.

write (15301,[
    Type,
    GoodsList
] = Src_Data) ->
    BinList_GoodsList = [
        item_to_bin_0(GoodsList_Item) || GoodsList_Item <- GoodsList
    ], 

    GoodsList_Len = length(GoodsList), 
    Bin_GoodsList = list_to_binary(BinList_GoodsList),

    Data = <<
        Type:8,
        GoodsList_Len:16, Bin_GoodsList/binary
    >>,
    {ok, pt:encode(15301, Data, Src_Data)};

write (15302,[
    Result,
    KeyList
] = Src_Data) ->
    BinList_KeyList = [
        item_to_bin_1(KeyList_Item) || KeyList_Item <- KeyList
    ], 

    KeyList_Len = length(KeyList), 
    Bin_KeyList = list_to_binary(BinList_KeyList),

    Data = <<
        Result:32,
        KeyList_Len:16, Bin_KeyList/binary
    >>,
    {ok, pt:encode(15302, Data, Src_Data)};

write (15304,[
    Res,
    GoodsId,
    Num,
    BuyType
] = Src_Data) ->
    Data = <<
        Res:32,
        GoodsId:32,
        Num:32,
        BuyType:8
    >>,
    {ok, pt:encode(15304, Data, Src_Data)};

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


item_to_bin_0 ({
    KeyId,
    Rank,
    GoodsId,
    Num,
    MoneyType,
    Price,
    Discount,
    QuotaType,
    QuotaNum,
    SoldOut,
    Condition,
    Bind,
    Preview
}) ->
    Bin_Condition = pt:write_string(Condition), 

    Data = <<
        KeyId:32,
        Rank:32,
        GoodsId:32,
        Num:32,
        MoneyType:8,
        Price:32,
        Discount:16,
        QuotaType:8,
        QuotaNum:16,
        SoldOut:16,
        Bin_Condition/binary,
        Bind:8,
        Preview:8
    >>,
    Data.
item_to_bin_1 ({
    KeyId,
    Num
}) ->
    Data = <<
        KeyId:32,
        Num:32
    >>,
    Data.
