%%% -------------------------------------------------------
%%% @author huangyongxing@yeah.net
%%% @doc
%%% 虚拟客户端管理器监控树
%%% @end
%%% -------------------------------------------------------
-module(cli_simu_sup).

-behaviour(supervisor).

%% API
-export([start_link/0]).

%% Supervisor callbacks
-export([init/1]).

-include("common.hrl").

-define(SERVER, ?MODULE).

start_link() ->
    supervisor:start_link({local, ?SERVER}, ?MODULE, []).

init([]) ->
    ?INFO_TTY("Start supervisor [~w] ...", [?SERVER]),
    %% {RestartStrategy, MaxR, MaxT}, MaxT秒内超过MaxR次重启，即停止监控树和子进程
    RestartStrategy = {one_for_one, 10, 5},
    Children = get_children(),
    {ok, {RestartStrategy, Children}}.

get_children() ->
    Children = [
        {cli_simu_mgr, start_link, []}
        ,{{cli_role_sup, start_link, []}, supervisor}
    ],
    [
        case format_child(ChildInfo) of
            false -> throw(error);
            Child -> Child
        end || ChildInfo <- Children
    ].

%% 将简易配置转换为supervisor的childspec格式
format_child({Mod, Fun, Args}) ->
    {Mod, {Mod, Fun, Args}, permanent, 10000, worker, [Mod]};
format_child({StartFunc = {Mod, _, _}, Type}) ->
    {Mod, StartFunc, permanent, 10000, Type, [Mod]};
format_child(Child = {_ChildName, _StartFunc = {_, _, _}, _Restart, _Shutdown, _Type, _Modules}) ->
    Child;
format_child(_) ->
    io:format("[~w:~w] supervisor child error format~n", [?MODULE, ?LINE]),
    false.

