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

read(13800, Bin0) ->
    <<Subtype:8, Bin1/binary>> = Bin0, 
    <<Opty:16, _Bin2/binary>> = Bin1, 
    {ok, [Subtype, Opty]};
read(13802, Bin0) ->
    <<Subtype:8, Bin1/binary>> = Bin0, 
    <<Map:16, Bin2/binary>> = Bin1, 
    <<Id:8, _Bin3/binary>> = Bin2, 
    {ok, [Subtype, Map, Id]};
read(13803, Bin0) ->
    <<Subtype:8, Bin1/binary>> = Bin0, 
    <<Map:16, Bin2/binary>> = Bin1, 
    <<Id:8, _Bin3/binary>> = Bin2, 
    {ok, [Subtype, Map, Id]};
read(_Cmd, _R) -> {error, no_match}.

write (13800,[
    Subtype,
    Opty,
    MapTasks
] = Src_Data) ->
    BinList_MapTasks = [
        item_to_bin_0(MapTasks_Item) || MapTasks_Item <- MapTasks
    ], 

    MapTasks_Len = length(MapTasks), 
    Bin_MapTasks = list_to_binary(BinList_MapTasks),

    Data = <<
        Subtype:8,
        Opty:16,
        MapTasks_Len:16, Bin_MapTasks/binary
    >>,
    {ok, pt:encode(13800, Data, Src_Data)};

write (13801,[
    Subtype,
    Map,
    Id,
    State,
    Value,
    Grade
] = Src_Data) ->
    Data = <<
        Subtype:8,
        Map:16,
        Id:8,
        State:8,
        Value:16,
        Grade:8
    >>,
    {ok, pt:encode(13801, Data, Src_Data)};

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

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

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


item_to_bin_0 ({
    Map,
    Tasks
}) ->
    BinList_Tasks = [
        item_to_bin_1(Tasks_Item) || Tasks_Item <- Tasks
    ], 

    Tasks_Len = length(Tasks), 
    Bin_Tasks = list_to_binary(BinList_Tasks),

    Data = <<
        Map:16,
        Tasks_Len:16, Bin_Tasks/binary
    >>,
    Data.
item_to_bin_1 ({
    Id,
    State,
    Value,
    Grade
}) ->
    Data = <<
        Id:8,
        State:8,
        Value:16,
        Grade:8
    >>,
    Data.
