%%%-------------------------------------------------------------------
%% @doc iot top level supervisor.
%% @end
%%%-------------------------------------------------------------------

-module(iot_sup).
-behaviour(supervisor).

-export([start_link/0]).

-export([init/1]).

-define(SERVER, ?MODULE).

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

%% sup_flags() = #{strategy => strategy(),         % optional
%%                 intensity => non_neg_integer(), % optional
%%                 period => pos_integer()}        % optional
%% child_spec() = #{id => child_id(),       % mandatory
%%                  start => mfargs(),      % mandatory
%%                  restart => restart(),   % optional
%%                  shutdown => shutdown(), % optional
%%                  type => worker(),       % optional
%%                  modules => modules()}   % optional
init([]) ->
    SupFlags = #{strategy => one_for_one, intensity => 10, period => 36},

    Specs = [
        #{
            id => 'iot_container_task_sup',
            start => {'iot_container_task_sup', start_link, []},
            restart => permanent,
            shutdown => 2000,
            type => supervisor,
            modules => ['iot_container_task_sup']
        },

        #{
            id => 'udp_server',
            start => {'udp_server', start_link, []},
            restart => permanent,
            shutdown => 2000,
            type => worker,
            modules => ['udp_server']
        },

        #{
            id => 'ctrl_server',
            start => {'ctrl_server', start_link, []},
            restart => permanent,
            shutdown => 2000,
            type => worker,
            modules => ['ctrl_server']
        },

        #{
            id => 'iot_host_sup',
            start => {'iot_host_sup', start_link, []},
            restart => permanent,
            shutdown => 2000,
            type => supervisor,
            modules => ['iot_host_sup']
        }
    ],

    {ok, {SupFlags, pools() ++ Specs}}.

%% internal functions

pools() ->
    case application:get_env(iot, pools) of
        undefined ->
            [];
        {ok, Pools} ->
            lists:map(fun({Name, PoolArgs, WorkerArgs}) ->
                poolboy:child_spec(Name, [{name, {local, Name}}|PoolArgs], WorkerArgs)
                      end, Pools)
    end.
