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

read(40400, _) ->
    {ok, []};
read(40402, _) ->
    {ok, []};
read(40403, Bin0) ->
    <<Opty:8, _Bin1/binary>> = Bin0, 
    {ok, [Opty]};
read(40405, _) ->
    {ok, []};
read(40407, Bin0) ->
    <<Id:16, _Bin1/binary>> = Bin0, 
    {ok, [Id]};
read(_Cmd, _R) -> {error, no_match}.

write (40400,[
    Labors,
    Stage,
    LaborTasks
] = Src_Data) ->
    BinList_LaborTasks = [
        item_to_bin_0(LaborTasks_Item) || LaborTasks_Item <- LaborTasks
    ], 

    LaborTasks_Len = length(LaborTasks), 
    Bin_LaborTasks = list_to_binary(BinList_LaborTasks),

    Data = <<
        Labors:32,
        Stage:16,
        LaborTasks_Len:16, Bin_LaborTasks/binary
    >>,
    {ok, pt:encode(40400, Data, Src_Data)};

write (40401,[
    Id,
    Type,
    Progress,
    State
] = Src_Data) ->
    Data = <<
        Id:16,
        Type:8,
        Progress:8,
        State:8
    >>,
    {ok, pt:encode(40401, Data, Src_Data)};

write (40402,[
    Labors,
    Stime,
    Stage
] = Src_Data) ->
    Data = <<
        Labors:32,
        Stime:32,
        Stage:16
    >>,
    {ok, pt:encode(40402, Data, Src_Data)};

write (40403,[
    Opty,
    Result,
    Stage
] = Src_Data) ->
    Data = <<
        Opty:8,
        Result:32,
        Stage:16
    >>,
    {ok, pt:encode(40403, Data, Src_Data)};

write (40404,[
    Type,
    Name,
    Value,
    Time
] = Src_Data) ->
    Bin_Name = pt:write_string(Name), 

    Data = <<
        Type:8,
        Bin_Name/binary,
        Value:16,
        Time:32
    >>,
    {ok, pt:encode(40404, Data, Src_Data)};

write (40405,[
    Logs
] = Src_Data) ->
    BinList_Logs = [
        item_to_bin_1(Logs_Item) || Logs_Item <- Logs
    ], 

    Logs_Len = length(Logs), 
    Bin_Logs = list_to_binary(BinList_Logs),

    Data = <<
        Logs_Len:16, Bin_Logs/binary
    >>,
    {ok, pt:encode(40405, Data, Src_Data)};

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

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

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


item_to_bin_0 ({
    Id,
    Type,
    Progress,
    State
}) ->
    Data = <<
        Id:16,
        Type:8,
        Progress:8,
        State:8
    >>,
    Data.
item_to_bin_1 ({
    Type,
    Name,
    Value,
    Time
}) ->
    Bin_Name = pt:write_string(Name), 

    Data = <<
        Type:8,
        Bin_Name/binary,
        Value:16,
        Time:32
    >>,
    Data.
