%%% -------------------------------------------------------
%%% @author huangyongxing@yeah.net
%%% @doc
%%% 模拟的客户端，处理登录相关接口
%%% @end
%%% -------------------------------------------------------
-module(cli_login).
-export([
        handle/3
        , auth/2
        , read_single_role/1
    ]).
-include("cli_simu.hrl").

-define(SOURCE, localtest).

%% 请求进行账号登录验证
auth(AccId, AccName) ->
    Time = utime:unixtime(),
    Sign = make_sign(AccId, AccName, Time),
    cli_simu_proto:pack_send(10000, [AccId, Time, AccName, Sign]),
    ok.

%% 收到服务端返回10000，验证通过，获得角色列表
handle(10000, CliRole = #cli_role{account = AccName}, RoleList) ->
    case RoleList of
        [] ->   %% 无角色，创角
            %% TODO 这里可能还要相应调整Career，暂时全定1
            Realm  = 1,
            Career = 1,
            Sex = urand:rand(1, 2),
            Name = lists:sublist(util:md5(AccName), 8),
            Source = ?SOURCE,
            %% 请求执行创角操作
            cli_simu_proto:pack_send(10003, [Realm, Career, Sex, Name, Source]),
            ok;
        [_HeadRole = {_Status, Figure} | _] ->   %% 取得首个角色
            #figure{id = RoleId} = Figure,
            NewCliRole = CliRole#cli_role{id = RoleId, figure = Figure},
            do_login(NewCliRole),
            NewCliRole
    end;

%% 收到服务端返回10003（创角返回）
handle(10003, CliRole, [Code, Id]) ->
    case Code =:= 1 andalso Id > 0 of
        true  ->
            NewCliRole = CliRole#cli_role{id = Id},
            do_login(NewCliRole),
            NewCliRole;
        false ->
            throw({error, <<"create role failure">>})
    end;

%% 收到10004返回
handle(10004, _CliRole = #cli_role{id = RoleId, conn_pid = ConnPid}, _Result) ->
    %% 收到登录成功通知（忽略失败）
    %% 设置连接进程中的角色id值
    ConnPid ! {set_id, RoleId, self()},
    %% 异步获取本人信息
    cli_player:async_get_my_info(),
    %% 加载场景
    cli_scene:async_load_scene(),
    ok;

handle(_, _, _) ->
    ignore.

%% 内部接口
make_sign(AccId, AccName, Time) ->
    Ticket =
    case application:get_env(main, ticket) of
        {ok, TicketX} -> TicketX;
        _ -> "SDFSDESF123DFSDF"
    end,
    StrAccName = util:make_sure_list(AccName),
    util:md5(lists:concat([AccId, StrAccName, Time, Ticket])).

%% 执行登录操作
do_login(_CliRole = #cli_role{id = RoleId}) ->
    % ?INFO_TTY("pack send 10004"),
    cli_simu_proto:pack_send(10004, [RoleId, "lt-svr", utime:unixtime(), "", 0]),
    ok.

%% 读取角色列表中的单个角色
read_single_role(<<_Status:8, RestBin0/binary>>) ->
    {Figure, RestBin1} = cli_simu_proto:read_figure(RestBin0),
    {{_Status, Figure}, RestBin1}.

