%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2024, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 11. 7月 2024 15:54
%%%-------------------------------------------------------------------
-module(iot_event_period_settings).
-author("anlicheng").
-include_lib("stdlib/include/qlc.hrl").

-behaviour(gen_server).

%% API
-export([start_link/0]).
-export([get_throttle/1, debug_info/0]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-define(SERVER, ?MODULE).

-define(TAB_NAME, iot_ets_event_period).

%% 更新周期, 单位：秒
-define(UPDATE_TICKER, 300).

%% 默认周期, 单位：秒
-define(DEFAULT_THROTTLE, 300).

-record(state, {

}).

-record(period, {
    group_key :: any(),
    throttle :: integer()
}).

%%%===================================================================
%%% API
%%%===================================================================

debug_info() ->
    Q = qlc:q([E || E <- ets:table(?TAB_NAME)]),
    qlc:e(Q).

%% 获取设置的时间周期
-spec get_throttle(GroupKey :: any()) -> integer().
get_throttle(GroupKey) ->
    case ets:lookup(?TAB_NAME, GroupKey) of
        [] ->
            ?DEFAULT_THROTTLE;
        [#period{throttle = Throttle}|_] ->
            Throttle
    end.

%% @doc Spawns the server and registers the local name (unique)
-spec(start_link() ->
    {ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link() ->
    gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).

%%%===================================================================
%%% gen_server callbacks
%%%===================================================================

%% @private
%% @doc Initializes the server
-spec(init(Args :: term()) ->
    {ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term()} | ignore).
init([]) ->
    ets:new(?TAB_NAME, [public, set, named_table, {keypos, 2}, {read_concurrency, true}]),
    erlang:start_timer(0, self(), update_ticker),
    {ok, #state{}}.

%% @private
%% @doc Handling call messages
-spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()},
    State :: #state{}) ->
    {reply, Reply :: term(), NewState :: #state{}} |
    {reply, Reply :: term(), NewState :: #state{}, timeout() | hibernate} |
    {noreply, NewState :: #state{}} |
    {noreply, NewState :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
    {stop, Reason :: term(), NewState :: #state{}}).
handle_call(_Request, _From, State = #state{}) ->
    {reply, ok, State}.

%% @private
%% @doc Handling cast messages
-spec(handle_cast(Request :: term(), State :: #state{}) ->
    {noreply, NewState :: #state{}} |
    {noreply, NewState :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term(), NewState :: #state{}}).
handle_cast(_Request, State = #state{}) ->
    {noreply, State}.

%% @private
%% @doc Handling all non call/cast messages
-spec(handle_info(Info :: timeout() | term(), State :: #state{}) ->
    {noreply, NewState :: #state{}} |
    {noreply, NewState :: #state{}, timeout() | hibernate} |
    {stop, Reason :: term(), NewState :: #state{}}).
handle_info({timeout, _, update_ticker}, State = #state{}) ->
    catch settings(),
    erlang:start_timer(?UPDATE_TICKER * 1000, self(), update_ticker),
    {noreply, State}.

%% @private
%% @doc This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
%% with Reason. The return value is ignored.
-spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
    State :: #state{}) -> term()).
terminate(_Reason, _State = #state{}) ->
    ok.

%% @private
%% @doc Convert process state when code is changed
-spec(code_change(OldVsn :: term() | {down, term()}, State :: #state{},
    Extra :: term()) ->
    {ok, NewState :: #state{}} | {error, Reason :: term()}).
code_change(_OldVsn, State = #state{}, _Extra) ->
    {ok, State}.

%%%===================================================================
%%% Internal functions
%%%===================================================================

-spec settings() -> no_return().
settings() ->
    case iot_api:get_event_period_settings() of
        {ok, Resp} ->
            case catch jiffy:decode(Resp, [return_maps]) of
                #{<<"code">> := 200, <<"data">> := Settings} when is_list(Settings) ->
                    lists:foreach(fun(#{<<"event_code">> := GroupKey, <<"time_period">> := Throttle}) ->
                        case is_integer(Throttle) andalso Throttle > 0 of
                            true ->
                                ets:insert(?TAB_NAME, #period{group_key = GroupKey, throttle = Throttle});
                            false ->
                                ok
                        end
                                  end, Settings);
                Error ->
                    lager:debug("[iot_event_period_settings] get event_period_settings from api get error: ~p", [Error])
            end;
        {error, Reason} ->
            lager:debug("[iot_event_period_settings] get event_period_settings from api get error: ~p", [Reason])
    end.