%%% -------------------------------------------------------
%%% @author huangyongxing@yeah.net
%%% @doc
%%% 模拟客户端公共接口
%%% @end
%%% -------------------------------------------------------
-module(cli_simu_utils).
-export([
        errlog/4
        , info/4
        , debug/4
        , log_file/1
        , log_file/2
        , log_file/5
    ]).

%% -------------------------------------------------------------------
%% 日志处理
%% -------------------------------------------------------------------

%% 下面的接口与util中的接口写入文件不一样
errlog(Format, Args, Mod, Line) -> log_file("ERROR", Format, Args, Mod, Line).
info(Format, Args, Mod, Line)   -> log_file("INFO",  Format, Args, Mod, Line).
debug(Format, Args, Mod, Line)  -> log_file("DEBUG", Format, Args, Mod, Line).

%% 日志记录函数
log_file(Format) ->
    log_file(error, Format, [], undefined, undefined).
log_file(Format, Args) ->
    log_file(error, Format, Args, undefined, undefined).
log_file(Tag, Format, Args, Mod, Line) ->
    {{Y, M, D}, {H, I, S}} = erlang:localtime(),
    TagLower = util:strip(util:change_case(lower, Tag)),
    FDKey = {fd, TagLower},
    FH =
    case get(FDKey) of
        {IoDevice, Y, M, D} ->
            IoDevice;
        Other ->
            Pre = "cli_",
            LogPath = "../logs/",
            File =
            case lists:member(TagLower, [<<"error">>, <<"info">>, <<"debug">>]) of
                true  -> util:fmt_bin("~ts/~ts~4..0w_~2..0w_~2..0w.txt", [LogPath, Pre, Y, M, D]);
                false -> util:fmt_bin("~ts/~ts~ts_~4..0w_~2..0w_~2..0w.txt", [LogPath, Pre, TagLower, Y, M, D])
            end,
            {ok, IoDevice} = file:open(File, [write, append, {encoding, utf8}]),
            put(FDKey, {IoDevice, Y, M, D}),
            case Other of
                {OldIoDevice, _, _, _} -> file:close(OldIoDevice);
                _ -> ignore
            end,
            IoDevice
    end,
    DateTime = io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w", [Y, M, D, H, I, S]),
    case {Mod, Line} =:= {undefined, undefined} of
        true  ->
            NewFormat = unicode:characters_to_list(lists:concat(["#", Tag, " ~ts\n", Format, "\n\n"])),
            io:format(FH, NewFormat, [DateTime | Args]);
        false ->
            NewFormat = unicode:characters_to_list(lists:concat(["#", Tag, " ~ts[~w:~w]\n", Format, "\n\n"])),
            io:format(FH, NewFormat, [DateTime, Mod, Line | Args])
    end.

