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

read(42200, _) ->
    {ok, []};
read(42202, Bin0) ->
    <<StoreId:8, _Bin1/binary>> = Bin0, 
    {ok, [StoreId]};
read(42203, Bin0) ->
    <<StoreId:8, Bin1/binary>> = Bin0, 
    <<GtypeId:32, Bin2/binary>> = Bin1, 
    <<BuyTimes:32, _Bin3/binary>> = Bin2, 
    {ok, [StoreId, GtypeId, BuyTimes]};
read(_Cmd, _R) -> {error, no_match}.

write (42200,[
    Stage,
    SumWardrobeValue,
    WardrobeList
] = Src_Data) ->
    BinList_WardrobeList = [
        item_to_bin_0(WardrobeList_Item) || WardrobeList_Item <- WardrobeList
    ], 

    WardrobeList_Len = length(WardrobeList), 
    Bin_WardrobeList = list_to_binary(BinList_WardrobeList),

    Data = <<
        Stage:8,
        SumWardrobeValue:32,
        WardrobeList_Len:16, Bin_WardrobeList/binary
    >>,
    {ok, pt:encode(42200, Data, Src_Data)};

write (42201,[
    Stage,
    SumWardrobeValue,
    Type,
    WardrobeValue,
    Collect,
    SumCollect,
    Id,
    Color
] = Src_Data) ->
    Data = <<
        Stage:8,
        SumWardrobeValue:32,
        Type:8,
        WardrobeValue:32,
        Collect:8,
        SumCollect:8,
        Id:32,
        Color:8
    >>,
    {ok, pt:encode(42201, Data, Src_Data)};

write (42202,[
    StoreId,
    GoodsList
] = Src_Data) ->
    BinList_GoodsList = [
        item_to_bin_1(GoodsList_Item) || GoodsList_Item <- GoodsList
    ], 

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

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

write (42203,[
    Res,
    StoreId,
    Pos,
    GtypeId,
    Num
] = Src_Data) ->
    Data = <<
        Res:32,
        StoreId:8,
        Pos:16,
        GtypeId:32,
        Num:32
    >>,
    {ok, pt:encode(42203, Data, Src_Data)};

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


item_to_bin_0 ({
    Type,
    WardrobeValue,
    Collect,
    SumCollect
}) ->
    Data = <<
        Type:8,
        WardrobeValue:32,
        Collect:8,
        SumCollect:8
    >>,
    Data.
item_to_bin_1 ({
    Pos,
    GtypeId,
    Num
}) ->
    Data = <<
        Pos:16,
        GtypeId:32,
        Num:32
    >>,
    Data.
