%% ---------------------------------------------------------------------------
%% @doc lib_log
%% @author ming_up@foxmail.com
%% @since  2016-07-28
%% @deprecated 日志系统库函数
%% ---------------------------------------------------------------------------
-module(lib_log).
-include("common.hrl").
-export([to_db/2]).

%% Note: 旧版插入顺序是反序的，改版后已经是正序。并对部分模块传错参数做了最基本的检查
to_db(Type, ArgsList = [_|_]) ->
    case catch execute_db(Type, ArgsList) of
        {'EXIT', Reason} ->
            ?PRINT("log format error Type:~p, ArgsList:~n~p ~nReason:~p~n", [Type, ArgsList, Reason]),
            ?ERR("log format error Type:~p, ArgsList:~n~p ~nReason:~n~p~n", [Type, ArgsList, Reason]);
        _ -> ok
    end;
to_db(_, _) ->
    ignore.

execute_db(Type, ArgsList) ->
    {TableName, Columns} = data_log:get_log(Type),
    case lists:foldl(fun to_sql_values/2, "", ArgsList) of
        [_|_] = SqlValuesString ->
            Sql = lists:concat(["INSERT INTO ", TableName, " (", Columns, ") VALUES ", SqlValuesString]),
            db:execute(Sql);
        _Empty ->   % 没有合法的数据
            ignore
    end.

%% lists:foldl中使用的Function
to_sql_values(Args = [_|_], AccStr) ->
    One = to_sql_string_helper(Args, []),
    OneValue = lists:concat(["(", One, ")"]),
    case AccStr of
        "" -> OneValue;
        _  -> lists:concat([AccStr, ",", OneValue])
    end;
to_sql_values(_ErrArgs, AccStr) ->
    %% 屏蔽部分模块用错的数据格式，通常是个空列表
    AccStr.

to_sql_string_helper([H], Result) ->
    lists:concat(lists:reverse(["'", uio:thing_to_string(H), "'"| Result]));
to_sql_string_helper([H|T], Result) ->
    to_sql_string_helper(T, ["', ", uio:thing_to_string(H), "'"| Result]).
