package tasksch

import (
	"sort"
	"time"

	"git.rosy.net.cn/jx-callback/business/jxutils"
)

const (
	defLastHours  = 24
	maxStoreHours = 48 // 最多存放小时数
)

var (
	defTaskMan TaskMan
)

type TaskMan struct {
	taskMap jxutils.SyncMapWithTimeout
}

func init() {
}

func (m *TaskMan) GetTasks(taskID string, fromStatus, toStatus int, lastHours int, createdBy string) (taskList TaskList) {
	if lastHours == 0 {
		lastHours = defLastHours
	}
	lastTime := time.Now().Add(time.Duration(-lastHours) * time.Hour).Unix()
	m.taskMap.Range(func(key, value interface{}) bool {
		k := key.(string)
		v := value.(ITask)
		status := v.GetStatus()
		if !((createdBy != "" && createdBy != v.GetCreatedBy()) || (taskID != "" && taskID != k) || status < fromStatus || status > toStatus || v.GetCreatedAt().Unix() < lastTime) {
			taskList = append(taskList, v)
		}
		return true
	})
	sort.Sort(TaskList(taskList))
	return taskList
}

func (m *TaskMan) ManageTask(task ITask) ITask {
	m.taskMap.StoreWithTimeout(task.GetID(), task, maxStoreHours*time.Hour)
	return task
}

func GetTasks(taskID string, fromStatus, toStatus int, lastHours int, createdBy string) (taskList TaskList) {
	return defTaskMan.GetTasks(taskID, fromStatus, toStatus, lastHours, createdBy)
}

func ManageTask(task ITask) ITask {
	return defTaskMan.ManageTask(task)
}

func IsTaskRunning(taskID string) bool {
	if taskList := GetTasks(taskID, TaskStatusBegin, TaskStatusWorking, 0, ""); len(taskList) > 0 {
		return true
	}
	return false
}

func UnmanageTasks(taskIDs []string) {
	if len(taskIDs) == 0 {
		allTasks := GetTasks("", TaskStatusBegin, TaskStatusEnd, maxStoreHours, "")
		for _, v := range allTasks {
			taskIDs = append(taskIDs, v.GetID())
		}
	}
	for _, v := range taskIDs {
		defTaskMan.taskMap.Delete(v)
	}
}
