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

read(45201, _) ->
    {ok, []};
read(45202, Bin0) ->
    <<Category:16, _Bin1/binary>> = Bin0, 
    {ok, [Category]};
read(45203, Bin0) ->
    <<Category:16, Bin1/binary>> = Bin0, 
    <<TaskId:16, _Bin2/binary>> = Bin1, 
    {ok, [Category, TaskId]};
read(_Cmd, _R) -> {error, no_match}.

write (45201,[
    CategoryList
] = Src_Data) ->
    BinList_CategoryList = [
        item_to_bin_0(CategoryList_Item) || CategoryList_Item <- CategoryList
    ], 

    CategoryList_Len = length(CategoryList), 
    Bin_CategoryList = list_to_binary(BinList_CategoryList),

    Data = <<
        CategoryList_Len:16, Bin_CategoryList/binary
    >>,
    {ok, pt:encode(45201, Data, Src_Data)};

write (45202,[
    Errcode,
    Category
] = Src_Data) ->
    Data = <<
        Errcode:32,
        Category:16
    >>,
    {ok, pt:encode(45202, Data, Src_Data)};

write (45203,[
    Errcode,
    Category,
    TaskId
] = Src_Data) ->
    Data = <<
        Errcode:32,
        Category:16,
        TaskId:16
    >>,
    {ok, pt:encode(45203, Data, Src_Data)};

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


item_to_bin_0 ({
    Category,
    TaskList
}) ->
    BinList_TaskList = [
        item_to_bin_1(TaskList_Item) || TaskList_Item <- TaskList
    ], 

    TaskList_Len = length(TaskList), 
    Bin_TaskList = list_to_binary(BinList_TaskList),

    Data = <<
        Category:16,
        TaskList_Len:16, Bin_TaskList/binary
    >>,
    Data.
item_to_bin_1 ({
    TaskId,
    Progress,
    Status
}) ->
    Data = <<
        TaskId:16,
        Progress:32,
        Status:8
    >>,
    Data.
