package task

import (
	"strings"
)

func overlayTaskDetailUnread(runtime TaskUnreadRuntime, workspaceID string, memberID string, detail *TaskDetail) {
	if detail == nil {
		return
	}
	overlayTaskUnread(runtime, workspaceID, memberID, &detail.Task)
}

func overlayTaskUnread(runtime TaskUnreadRuntime, workspaceID string, memberID string, task *Task) {
	if runtime == nil || task == nil || task.ReadState == nil {
		return
	}
	scopeID := taskRuntimeScopeID(*task)
	if scopeID == "" {
		return
	}
	states := runtime.ScopeStates(workspaceID, memberID, []string{scopeID})
	state, ok := states[scopeID]
	if !ok {
		task.ReadState.UnreadCount = 0
		task.ReadState.ManualUnread = false
		return
	}
	task.ReadState.UnreadCount = state.Count()
	task.ReadState.ManualUnread = state.ManualUnread
}

func overlayRelatedTaskUnread(runtime TaskUnreadRuntime, workspaceID string, memberID string, rows []RelatedTaskRow) {
	for index := range rows {
		rows[index].Unread = RelatedTaskUnread{}
	}
	if runtime == nil || len(rows) == 0 {
		return
	}
	scopeIDs := make([]string, 0, len(rows))
	seen := make(map[string]struct{}, len(rows))
	for _, row := range rows {
		scopeID := taskRuntimeScopeIDFromParts(row.TaskID, row.TaskScopeID)
		if scopeID == "" {
			continue
		}
		if _, ok := seen[scopeID]; ok {
			continue
		}
		seen[scopeID] = struct{}{}
		scopeIDs = append(scopeIDs, scopeID)
	}
	states := runtime.ScopeStates(workspaceID, memberID, scopeIDs)
	for index := range rows {
		scopeID := taskRuntimeScopeIDFromParts(rows[index].TaskID, rows[index].TaskScopeID)
		state, ok := states[scopeID]
		if !ok {
			continue
		}
		rows[index].Unread = RelatedTaskUnread{Count: state.Count(), ManualUnread: state.ManualUnread}
	}
}

func taskRuntimeScopeID(task Task) string {
	return taskRuntimeScopeIDFromParts(task.ID, task.TaskScopeID)
}

func taskRuntimeScopeIDFromParts(taskID string, taskScopeID string) string {
	if scopeID := strings.TrimSpace(taskScopeID); scopeID != "" {
		return scopeID
	}
	return strings.TrimSpace(taskID)
}
