/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: LogUtil
 * @Package cn.freemud.utils
 * @Description:
 * @author: liming.guo
 * @date: 2018/7/3 12:01
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.utils;

import cn.freemud.base.ApplicationContextWare;
import com.alibaba.fastjson.JSON;
import com.freemud.application.sdk.api.log.ApiLog;
import com.freemud.application.sdk.api.log.ErrorLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

@Component
public class LogUtil {

    @Value("${print-debug-log:false}")
    private boolean printDebug;

    private static Logger logger = LoggerFactory.getLogger(LogUtil.class);

    private static volatile String appName = "NO_APP_NAME";

    public void debug(String message, Object... params) {
        if (logger.isDebugEnabled()) {
            this.info(message, params);
        }
    }
    public void info(String message, Object... params) {
        if (printDebug) {
            Object[] clone = params != null ? params.clone() : new String[]{};
            String param1 = "", param2 = "", param3 = "";
            if (params.length > 0) {
                param1 = clone[0] instanceof String ? (String) clone[0] : JSON.toJSONString(clone[0]);
            }
            if (params.length > 1) {
                param2 = clone[1] instanceof String ? (String) clone[1] : JSON.toJSONString(clone[1]);
            }
            if (params.length > 2) {
                param3 = clone[2] instanceof String ? (String) clone[2] : JSON.toJSONString(clone[2]);
            }
            try {
                ApiLog.printLog(MessageFormat.format(message, params), param1, param2, param3);
            } catch (Exception e) {
                ErrorLog.errorDev("LogUtil.printLog ".concat(message), e, params);
            }
        }
    }
    public void error(String message, Exception e, String... params) {
        ErrorLog.errorDev(message, e, params);
    }

    private static String getAppName() {
        if (appName == null) {
            appName = ApplicationContextWare.getAppName();
            if (appName == null) {
                appName = "NO_APP_NAME";
            }
        }
        return appName;
    }


    public void errorSe(String message, Exception e, String... params) {
        ErrorLog.errorSe(message, e, params);
    }
}
