package cd.casic.framework.commons.util.watcher;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

/**
 * @author by mianbin
 * @Classname Watcher
 * @Description 针对running值导致抛出异常的位置主动做了stop，并增加了一个全部耗时统计
 * @Date 2025/3/18 10:49
 */
@Slf4j
public class Watcher extends StopWatch {

    @Getter
    private long createTime = System.currentTimeMillis();

    public Watcher(String id) {
        super(id);
        this.createTime = System.currentTimeMillis();
    }

    public long elapsed() {
        return System.currentTimeMillis() - createTime;
    }

    @Override
    public void start() {
        if (isRunning()) {
            stop();
        }
        super.start();
    }

    @Override
    public void start(String taskName) {
        if (isRunning()) {
            stop();
        }
        super.start(taskName);
    }

    @Override
    public String toString() {
        if (isRunning()) {
            stop();
        }
        StringBuilder sb = new StringBuilder(shortSummary());
        for (TaskInfo task : this.getTaskInfo()) {
            sb.append("|").append(task.getTaskName()).append("=").append(task.getTimeMillis());
        }
        return sb.toString();
    }

    @Override
    public String shortSummary() {
        return "watcher|" + getId() + "|total=" + getTotalTimeMillis() + "|elapsed=" + elapsed();
    }

    @Override
    public void stop() {
        if (isRunning()) {
            try {
                super.stop();
            } catch (IllegalStateException ignored) {
            }
        }
    }

    public void safeAround(String taskName, Runnable action) {
        try {
            this.start(taskName);
            action.run();
        } catch (Exception e) {
            log.warn(getId() + " , " + taskName, e);
        } finally {
            this.stop();
        }
    }

}
