package cache

import (
	"jannex/admin-dashboard-backend/modules/structs"
	"jannex/admin-dashboard-backend/modules/utils"
	"sync"
	"time"
)

var lockedGroupTaskSteps []*structs.LockedGroupTaskSteps
var lgtMu sync.RWMutex

func AddLockedGroupTaskStep(lockedGroupTaskStep structs.LockedGroupTaskSteps) {
	lgtMu.Lock()

	var isAlreadyInList = false

	for i, step := range lockedGroupTaskSteps {
		if step.GroupTaskId == lockedGroupTaskStep.GroupTaskId &&
			lockedGroupTaskSteps[i].LockedByUserId == lockedGroupTaskStep.LockedByUserId {
			isAlreadyInList = true
			lockedGroupTaskSteps[i].LockedAt = time.Now()
			lockedGroupTaskSteps[i].RememberId = lockedGroupTaskStep.RememberId
			break
		}
	}

	if !isAlreadyInList {
		lockedGroupTaskSteps = append(lockedGroupTaskSteps, &lockedGroupTaskStep)
	}

	lgtMu.Unlock()
}

func RemoveLockedGroupTaskStep(i int) {
	lgtMu.Lock()
	lockedGroupTaskSteps = append(lockedGroupTaskSteps[:i], lockedGroupTaskSteps[i+1:]...)
	lgtMu.Unlock()
}

func GetLockedGroupTaskSteps() []*structs.LockedGroupTaskSteps {
	lgtMu.RLock()
	defer lgtMu.RUnlock()

	return lockedGroupTaskSteps
}

func ExtendLockedGroupTaskStepLockedAtTime(lockedGroupTaskStep structs.LockedGroupTaskSteps) {
	lgtMu.Lock()

	for i, step := range lockedGroupTaskSteps {
		if step.GroupTaskId == lockedGroupTaskStep.GroupTaskId {
			step.LockedAt = time.Now().Add(utils.GroupTaskLockedTime * time.Second)
			lockedGroupTaskSteps[i] = step
			break
		}
	}

	lgtMu.Unlock()
}
