%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2024, <COMPANY>
%%% @doc
%%% 事件发布器，提供基于时间周期的缓冲
%%% @end
%%% Created : 11. 7月 2024 14:40
%%%-------------------------------------------------------------------
-module(iot_event_publisher).
-author("anlicheng").

-behaviour(gen_server).

%% API
-export([start_link/1, publish/3]).

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

-define(SERVER, ?MODULE).

-record(state, {
    device_uuid :: binary(),
    group_buffers = #{} :: map()
}).

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

-spec publish(Pid :: pid(), EventType :: integer(), Params :: map()) -> no_return().
publish(Pid, EventType, Params) when is_pid(Pid), is_integer(EventType), is_map(Params) ->
    gen_server:cast(Pid, {publish, EventType, Params}).

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

%%%===================================================================
%%% 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([DeviceUUID]) ->
    {ok, #state{device_uuid = DeviceUUID}}.

%% @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({publish, EventType, Params}, State = #state{device_uuid = DeviceUUID, group_buffers = GroupBuffers}) ->
    GroupKey = group_by(EventType, Params),

    case maps:find(GroupKey, GroupBuffers) of
        {ok, Buffer} ->
            NBuffer = [{EventType, Params}|Buffer],
            {noreply, State#state{group_buffers = maps:put(GroupKey, NBuffer, GroupBuffers)}};
        error ->
            ThrottleTime = iot_event_period_settings:get_throttle(GroupKey),
            erlang:start_timer(ThrottleTime * 1000, self(), {throttle_ticker, GroupKey}),
            %% 发送消息
            iot_ai_router:batch_route_uuid(DeviceUUID, [{EventType, Params}]),
            {noreply, State#state{group_buffers = maps:put(GroupKey, [], GroupBuffers)}}
    end.

%% @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, _, {throttle_ticker, GroupKey}}, State = #state{device_uuid = DeviceUUID, group_buffers = GroupBuffers}) ->
    ThrottleTime = iot_event_period_settings:get_throttle(GroupKey),
    erlang:start_timer(ThrottleTime * 1000, self(), {throttle_ticker, GroupKey}),

    case maps:find(GroupKey, GroupBuffers) of
        {ok, Buffer} ->
            case length(Buffer) > 0 of
                true ->
                    iot_ai_router:batch_route_uuid(DeviceUUID, Buffer);
                false ->
                    ok
            end,
            {noreply, State#state{group_buffers = maps:put(GroupKey, [], GroupBuffers)}};
        error ->
            {noreply, State}
    end.

%% @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
%%%===================================================================

%% 事件分组函数
group_by(_EventType, #{<<"event_code">> := EventCode}) ->
    EventCode.