%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2024, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 30. 8月 2024 10:44
%%%-------------------------------------------------------------------
-module(iot_env).
-author("anlicheng").

%% 定义变量
-record(env, {
    key,
    val
}).

%% API
-export([new/0, reload/0, get_value/1, get_value/2]).

-spec new() -> ok.
new() ->
    ets:new(iot_env, [public, set, named_table, {read_concurrency, true}, {keypos, 2}]),
    Envs = load_env(),
    lager:debug("[iot_env] load envs: ~p", [Envs]),
    [ets:insert(iot_env, #env{key = Key, val = Val}) || {Key, Val} <- Envs],
    ok.

-spec reload() -> ok.
reload() ->
    Envs = load_env(),
    lager:debug("[iot_env] load envs: ~p", [Envs]),
    [ets:insert(iot_env, #env{key = Key, val = Val}) || {Key, Val} <- Envs],
    ok.

-spec get_value(Key :: atom()) -> any().
get_value(Key) when is_atom(Key) ->
    get_value(Key, undefined).

-spec get_value(Key :: atom(), Default :: any()) -> any().
get_value(Key, Default) when is_atom(Key) ->
    case ets:lookup(iot_env, Key) of
        [] ->
            Default;
        [#env{val = Val}|_] ->
            Val
    end.

-spec load_env() -> list().
load_env() ->
    Dir = code:priv_dir(iot),
    EnvFile = Dir ++ "/env.config",
    case file:read_file(EnvFile) of
        {ok, Content} ->
            {ok, Tokens, _} = erl_scan:string(binary_to_list(Content)),
            {ok, Forms} = erl_parse:parse_term(Tokens),
            Forms;
        {error, Reason} ->
            lager:warning("[iot] read .env file: ~p, get error: ~p", [EnvFile, Reason]),
            []
    end.