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

read(50101, _) ->
    {ok, []};
read(50102, Bin0) ->
    <<GoalId:8, Bin1/binary>> = Bin0,
    <<TaskId:8, _Bin2/binary>> = Bin1,
    {ok, [GoalId, TaskId]};
read(_Cmd, _R) -> {error, no_match}.

write (50100,[
    ErrorCode
]) ->
    Data = <<
        ErrorCode:32
    >>,
    {ok, pt:pack(50100, Data)};

write (50101,[
    GoalId,
    Status,
    TaskList,
    OpenTime
]) ->
    BinList_TaskList = [
        item_to_bin_0(TaskList_Item) || TaskList_Item <- TaskList
    ],

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

    Data = <<
        GoalId:8,
        Status:8,
        TaskList_Len:16, Bin_TaskList/binary,
        OpenTime:32
    >>,
    {ok, pt:pack(50101, Data)};

write (50102,[
    ErrorCode,
    GoalId,
    TaskId
]) ->
    Data = <<
        ErrorCode:32,
        GoalId:8,
        TaskId:8
    >>,
    {ok, pt:pack(50102, Data)};

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


item_to_bin_0 ({
    TaskId,
    Progress,
    Status,
    Extra
}) ->
    Bin_Extra = pt:write_string(Extra),

    Data = <<
        TaskId:8,
        Progress:32,
        Status:8,
        Bin_Extra/binary
    >>,
    Data.
