package com.yanzuoguang.util.log;


import com.yanzuoguang.util.helper.StringHelper;

import java.util.Date;

/**
 * 日志追踪器
 *
 * @author Light
 */
public class LogDate {
    public static final int MIN_MILL_SECOND = 1;

    private StringBuilder log = new StringBuilder();
    private long start = System.currentTimeMillis();
    private long end = System.currentTimeMillis();
    private double lastSecond = 0;
    private double totalSecond = 0;

    /**
     * 构造函数
     */
    public LogDate() {
        this("");
    }

    /**
     * 构造函数
     *
     * @param title 标记
     */
    public LogDate(String title) {
        this.clear();
        if (!StringHelper.isEmpty(title)) {
            this.begin(title);
        }
    }

    /**
     * 开始记录
     */
    public void begin() {
        this.start = System.currentTimeMillis();
    }

    /**
     * 开始标记
     *
     * @param title 开始标记
     */
    public void begin(String title) {
        this.begin();
        this.log.append(title);
    }

    /**
     * 提交日志,用于跟踪时间
     */
    public void commit() {
        this.end = System.currentTimeMillis();
        double total = this.end - this.start;
        this.lastSecond = total - this.totalSecond;
        this.totalSecond = total;
    }

    /**
     * 提交日志记录用于跟踪
     *
     * @param tag  标记
     * @param args 参数
     */
    public void commit(String tag, Object... args) {
        this.commit();
        if (!StringHelper.isEmpty(tag)) {
            String log = String.format("%s: %f ms 总共: %f ms ", String.format(tag, args), this.lastSecond, this.totalSecond);
            this.log.append(log);
        }
    }

    /**
     * 将当前日志对象复位
     */
    public void clear() {
        this.start = System.currentTimeMillis();
        this.end = System.currentTimeMillis();
        this.lastSecond = 0;
        this.totalSecond = 0;
        this.log = new StringBuilder();
    }

    /**
     * 将当前日志对象写入到日志中
     */
    public void write() {
        // 执行时间为0的不显示日志
        if (this.totalSecond >= MIN_MILL_SECOND) {
            String vLog = this.log.toString();
            if (!StringHelper.isEmpty(vLog)) {
                Log.info(LogDate.class, this.log.toString());
            }
            this.clear();
        }
    }

    /**
     * 获取日志内容
     *
     * @return
     */
    public StringBuilder getLog() {
        return this.log;
    }

    /**
     * 获取开始时间
     *
     * @return
     */
    public Date getStart() {
        return new Date(this.start) ;
    }

    /**
     * 获取结束时间
     *
     * @return
     */
    public Date getEnd() {
        return new Date(this.end);
    }

    /**
     * 获取最后处理时间
     *
     * @return
     */
    public double getLastSecond() {
        return this.lastSecond;
    }

    /**
     * 获取总执行时间
     *
     * @return
     */
    public double getTotalSecond() {
        return this.totalSecond;
    }
}