%%%-----------------------------------
%%% module  : pt_100
%%% @author  : xyao
%%% email   : jiexiaowen@gmail.com
%%% Created : 2010.04.29
%%% description: 注册登录系统
%%%-----------------------------------
-module(pt_100).
-export([read/2, write/2]).
-include("common.hrl").

%%
%%客户端 -> 服务端 ----------------------------
%%

%% 登陆
read(10000, <<AccId:32, Tstamp:32, Bin/binary>>) ->
    {AccName, Bin1} = pt:read_string(Bin),
    {Ticket, _} = pt:read_string(Bin1),
    {ok, [AccId, AccName, Tstamp, Ticket]};

%% 退出
read(10001, _) ->
    {ok, logout};

%% 创建角色
read(10003, <<Realm:8, Career:8, Sex:8, Bin/binary>>) ->
    {Name, Bin1} = pt:read_string_binary(Bin),
    {Source, Bin2} = pt:read_string(Bin1),
    <<IsDefault:8, IsSimulator:8, IsChangeName:8, Bin3/binary>> = Bin2,
    {TaGuestId, _} = pt:read_string_binary(Bin3),
    {ok, [Realm, Career, Sex, Name, Source, IsDefault, IsSimulator, IsChangeName, TaGuestId]};

%% 选择角色进入游戏
read(10004, <<Id:64, Bin/binary>>) ->
    {ServerName, Bin1} = pt:read_string_binary(Bin),
    <<Time:32, Bin2/binary>> = Bin1,
    {Ticket, Bin3} = pt:read_string(Bin2),
    <<NetworkType:8, Bin4/binary>> = Bin3,
    {LoginSource, Bin5} = pt:read_string_binary(Bin4),
    {TaGuestId, _} = pt:read_string_binary(Bin5),
    {ok, [Id, ServerName, Time, Ticket, NetworkType, LoginSource, TaGuestId]};

%% 删除角色
read(10005, <<Id:64>>) ->
    {ok, Id};

%% 心跳包
read(10006, _) ->
    {ok, heartbeat};


read(_Cmd, _R) ->
    {error, no_match}.

%%
%%服务端 -> 客户端 ------------------------------------
%%

%% 登陆返回
write(10000, [Career, Time, L, OpdayTime]) ->
    N = length(L),
    F = fun([Status, Figure, RegTime]) ->
            FigureBin = pt:write_figure(Figure),
            <<Status:8, FigureBin/binary, RegTime:32>>
    end,
    LB = list_to_binary([F(X) || X <- L]),
    {ok, pt:pack(10000, <<Career:8, Time:64, N:16, LB/binary, OpdayTime:32>>)};

%% 登陆退出
write(10001, _) ->
    Data = <<>>,
    {ok, pt:pack(10001, Data)};

%% 创建角色
write(10003, [Code, Id]) ->
    Data = <<Code:8, Id:64>>,
    {ok,  pt:pack(10003, Data)};

%% 选择角色进入游戏
write(10004, Code) ->
    Data = <<Code:8>>,
    {ok, pt:pack(10004, Data)};

%% 删除角色
write(10005, Code) ->
    Data = <<Code:16>>,
    {ok, pt:pack(10005, Data)};

%% 心跳包
write(10006, _) ->
    {ok, pt:pack(10006, <<>>)};

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

