%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2024, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 11. 7月 2024 17:01
%%%-------------------------------------------------------------------
-module(iot_api).
-author("anlicheng").

-define(API_TOKEN, <<"wv6fGyBhl*7@AsD9">>).

%% API
-export([ai_event/1, get_event_period_settings/0]).

-spec ai_event(Id :: integer()) -> no_return().
ai_event(Id) when is_integer(Id) ->
    Task = fun() ->
        Token = iot_util:md5(<<?API_TOKEN/binary, (integer_to_binary(Id))/binary, ?API_TOKEN/binary>>),
        {ok, Url0} = application:get_env(iot, api_url),
        Url = Url0 ++ "/api/v1/taskLog",

        Headers = [
            {<<"content-type">>, <<"application/json">>}
        ],
        ReqData = #{
            <<"token">> => Token,
            <<"id">> => Id
        },
        Body = iolist_to_binary(jiffy:encode(ReqData, [force_utf8])),
        case hackney:request(post, Url, Headers, Body, [{pool, false}]) of
            {ok, 200, _, ClientRef} ->
                {ok, RespBody} = hackney:body(ClientRef),
                lager:debug("[iot_api] send body: ~p, get error is: ~p", [Body, RespBody]),
                hackney:close(ClientRef);
            {ok, HttpCode, _, ClientRef} ->
                {ok, RespBody} = hackney:body(ClientRef),
                hackney:close(ClientRef),
                lager:warning("[iot_api] send body: ~p, get error is: ~p", [Body, {HttpCode, RespBody}]);
            {error, Reason} ->
                lager:warning("[iot_api] send body: ~p, get error is: ~p", [Body, Reason])
        end
           end,
    iot_task:submit(Task).

-spec get_event_period_settings() -> {ok, Resp :: binary()} | {error, Reason :: any()}.
get_event_period_settings() ->
    Token = iot_util:md5(<<?API_TOKEN/binary, ?API_TOKEN/binary>>),
    {ok, Url0} = application:get_env(iot, api_url),
    Url = Url0 ++ "/api/v1/alertPeriod",

    Headers = [
        {<<"content-type">>, <<"application/json">>}
    ],
    ReqData = #{
        <<"token">> => Token
    },
    Body = iolist_to_binary(jiffy:encode(ReqData, [force_utf8])),
    case hackney:request(post, Url, Headers, Body, [{pool, false}]) of
        {ok, 200, _, ClientRef} ->
            {ok, RespBody} = hackney:body(ClientRef),
            hackney:close(ClientRef),
            {ok, RespBody};
        {ok, HttpCode, _, ClientRef} ->
            hackney:close(ClientRef),
            {error, {http_error, HttpCode}};
        {error, Reason} ->
            {error, Reason}
    end.