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

read(15800, _) ->
    {ok, []};
read(15899, Bin0) ->
    <<ProductId:32, _Bin1/binary>> = Bin0, 
    {ok, [ProductId]};
read(15802, _) ->
    {ok, []};
read(15803, Bin0) ->
    <<ProductId:32, Bin1/binary>> = Bin0, 
    <<MoneyGap:32, Bin2/binary>> = Bin1, 
    <<IsQuick:8, _Bin3/binary>> = Bin2, 
    {ok, [ProductId, MoneyGap, IsQuick]};
read(_Cmd, _R) -> {error, no_match}.

write (15800,[
    ProductList
] = Src_Data) ->
    BinList_ProductList = [
        item_to_bin_0(ProductList_Item) || ProductList_Item <- ProductList
    ], 

    ProductList_Len = length(ProductList), 
    Bin_ProductList = list_to_binary(BinList_ProductList),

    Data = <<
        ProductList_Len:16, Bin_ProductList/binary
    >>,
    {ok, pt:encode(15800, Data, Src_Data)};

write (15801,[
    ProductId,
    ReturnType
] = Src_Data) ->
    Data = <<
        ProductId:32,
        ReturnType:8
    >>,
    {ok, pt:encode(15801, Data, Src_Data)};

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

write (15802,[
    DailyRechargeRecord,
    MonthRechargeRecord
] = Src_Data) ->
    BinList_DailyRechargeRecord = [
        item_to_bin_1(DailyRechargeRecord_Item) || DailyRechargeRecord_Item <- DailyRechargeRecord
    ], 

    DailyRechargeRecord_Len = length(DailyRechargeRecord), 
    Bin_DailyRechargeRecord = list_to_binary(BinList_DailyRechargeRecord),

    BinList_MonthRechargeRecord = [
        item_to_bin_2(MonthRechargeRecord_Item) || MonthRechargeRecord_Item <- MonthRechargeRecord
    ], 

    MonthRechargeRecord_Len = length(MonthRechargeRecord), 
    Bin_MonthRechargeRecord = list_to_binary(BinList_MonthRechargeRecord),

    Data = <<
        DailyRechargeRecord_Len:16, Bin_DailyRechargeRecord/binary,
        MonthRechargeRecord_Len:16, Bin_MonthRechargeRecord/binary
    >>,
    {ok, pt:encode(15802, Data, Src_Data)};

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

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


item_to_bin_0 ({
    ProductId,
    ReturnType
}) ->
    Data = <<
        ProductId:32,
        ReturnType:8
    >>,
    Data.
item_to_bin_1 ({
    GoldNum,
    Time
}) ->
    Data = <<
        GoldNum:64,
        Time:64
    >>,
    Data.
item_to_bin_2 ({
    GoldNum,
    Time
}) ->
    Data = <<
        GoldNum:64,
        Time:64
    >>,
    Data.
