%%%-------------------------------------------------------------------
%%% @author aresei
%%% @copyright (C) 2023, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 07. 9月 2023 17:07
%%%-------------------------------------------------------------------
-module(iot_logger).
-author("aresei").

-behaviour(gen_server).

%% API
-export([start_link/1, write/2]).

%% 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, {
    file_name :: string(),
    date :: calendar:date(),
    file
}).

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

write(Pid, Data) when is_pid(Pid) ->
    gen_server:cast(Pid, {write, Data}).

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

%%%===================================================================
%%% 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([FileName]) ->
    ensure_dir(),
    FilePath = make_file(FileName),
    {ok, File} = file:open(FilePath, [append, binary]),

    {ok, #state{file = File, file_name = FileName, date = get_date()}}.

%% @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({write, Data}, State = #state{file = OldFile, file_name = FileName, date = Date}) ->
    Line = <<(time_prefix())/binary, " ", (format(Data))/binary, $\n>>,
    case maybe_new_file(Date) of
        true ->
            file:close(OldFile),

            FilePath = make_file(FileName),
            {ok, File} = file:open(FilePath, [append, binary]),
            ok = file:write(File, Line),
            {noreply, State#state{file = File, date = get_date()}};
        false ->
            ok = file:write(OldFile, Line),
            {noreply, State}
    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(_Info, State = #state{}) ->
    {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
%%%===================================================================

format(Data) when is_binary(Data) ->
    iolist_to_binary(Data);
format(Items) when is_list(Items) ->
    iolist_to_binary(lists:join(<<"\t">>, Items)).

time_prefix() ->
    {{Y, M, D}, {H, I, S}} = calendar:local_time(),
    iolist_to_binary(io_lib:format("[~b-~2..0b-~2..0b ~2..0b:~2..0b:~2..0b]", [Y, M, D, H, I, S])).

-spec make_file(LogFile :: string()) -> string().
make_file(LogFile) when is_list(LogFile) ->
    {Year, Month, Day} = erlang:date(),
    Suffix = io_lib:format("~b~2..0b~2..0b", [Year, Month, Day]),
    RootDir = code:root_dir() ++ "/log/",
    lists:flatten(RootDir ++ LogFile ++ "." ++ Suffix).

ensure_dir() ->
    RootDir = code:root_dir() ++ "/log/",
    case filelib:is_dir(RootDir) of
        true ->
            ok;
        false ->
            file:make_dir(RootDir)
    end.

%% 获取日期信息
-spec get_date() -> Date :: calendar:date().
get_date() ->
    {Date, _} = calendar:local_time(),
    Date.

%% 通过日志判断是否需要生成新的日志文件
-spec maybe_new_file(Date :: calendar:date()) -> boolean().
maybe_new_file({Y, M, D}) ->
    {{Y0, M0, D0}, _} = calendar:local_time(),
    not (Y =:= Y0 andalso M =:= M0 andalso D =:= D0).