package com.ecep.contract.task;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import com.ecep.contract.Message;
import com.ecep.contract.TaskStatus;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 任务历史记录
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TaskHistory {
    private String taskId;
    private String title;
    private TaskStatus status;
    private long startTime;
    private long endTime;
    private String errorMessage;
    private List<Message> messages;

    /**
     * 获取任务执行耗时（毫秒）
     */
    public long getExecutionTime() {
        return endTime - startTime;
    }

    /**
     * 获取格式化的执行耗时
     */
    public String getFormattedExecutionTime() {
        long ms = getExecutionTime();
        if (ms < 1000) {
            return ms + "ms";
        } else if (ms < 60000) {
            return String.format("%.2fs", ms / 1000.0);
        } else {
            return String.format("%dm %.2fs", ms / 60000, (ms % 60000) / 1000.0);
        }
    }

    public TaskHistory(MonitoredTask<?> task, TaskStatus status2, long timeMillis, Object object) {
        this.taskId = task.getTaskId();
        this.title = task.titleProperty().get();
        this.status = status2;
        this.startTime = task.getStartTime();
        this.endTime = timeMillis;
        this.messages = new ArrayList<>(task.getMessages());

        if (object == null) {
            if (task.exceptionProperty().get() != null) {
                // 打印异常栈 到 字符串
                StringWriter sw = new StringWriter();
                task.exceptionProperty().get().printStackTrace(new java.io.PrintWriter(sw));
                String exceptionStack = sw.toString();
                setErrorMessage(exceptionStack);
            }
        } else {
            setErrorMessage(object.toString());

        }
    }
}
