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

-define(TAB, iot_device).

%% 定义变量
-record(device, {
    uuid
}).

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

-spec new() -> ok.
new() ->
    ets:new(?TAB, [public, set, named_table, {read_concurrency, true}, {keypos, 2}]),
    DeviceIds = load_file(),
    lager:debug("[iot_ignore_devices] load ids: ~p", [DeviceIds]),
    [ets:insert(?TAB, #device{uuid = Id}) || Id <- DeviceIds],
    ok.

-spec reload() -> ok.
reload() ->
    ets:delete_all_objects(?TAB),
    DeviceIds = load_file(),
    lager:debug("[iot_ignore_devices] load ids: ~p", [DeviceIds]),
    [ets:insert(?TAB, #device{uuid = Id}) || Id <- DeviceIds],
    ok.

-spec exists(Key :: binary()) -> boolean().
exists(Key) when is_binary(Key) ->
    case ets:lookup(?TAB, Key) of
        [] ->
            false;
        [#device{uuid = Key}|_] ->
            true
    end.

-spec load_file() -> list().
load_file() ->
    Dir = code:priv_dir(iot),
    EnvFile = Dir ++ "/weigang_light.txt",
    case file:read_file(EnvFile) of
        {ok, Content} ->
            Lines0 = binary:split(Content, <<$\n>>, [global, trim]),
            Lines1 = lists:map(fun(L) -> string:trim(L) end, Lines0),
            lists:filter(fun(L) -> string:trim(L) =/= <<"">> end, Lines1);
        {error, Reason} ->
            lager:warning("[iot] read .env file: ~p, get error: ~p", [EnvFile, Reason]),
            []
    end.