package cache

import (
	"jannex/robot-control-manager/modules/structs"
	"jannex/robot-control-manager/modules/utils"
	"sort"
	"sync"

	"git.ex.umbach.dev/Alex/roese-utils/rspagination"
)

// list of robots that are connected for the first time
// to this server and are not yet in the database (authorized)
var unauthorizedRobots = make(map[string]*structs.UnauthorizedRobot)
var urMu sync.RWMutex

func AddUnauthorizedRobot(robot *structs.UnauthorizedRobot) {
	urMu.Lock()
	defer urMu.Unlock()

	unauthorizedRobots[robot.Id] = robot
}

func GetUnauthorizedRobots() map[string]*structs.UnauthorizedRobot {
	urMu.RLock()
	defer urMu.RUnlock()

	return unauthorizedRobots
}

func GetAllUnauthorizedRobots(query rspagination.PageQuery) structs.UnauthorizedRobotsResponse {
	urMu.RLock()
	defer urMu.RUnlock()

	var r []structs.UnauthorizedRobot

	for _, v := range unauthorizedRobots {
		r = append(r, *v)
	}

	// sort after connected at
	sort.SliceStable(r, func(i, j int) bool {
		return r[i].ConnectedAt.After(r[j].ConnectedAt)
	})

	start, end := rspagination.GetPage(len(r), query.Page, utils.UnauthorizedRobotsPageLimit)

	return structs.UnauthorizedRobotsResponse{
		UnauthorizedRobots: r[start:end],
		TotalPages:         rspagination.CalculateTotalPages(len(r), utils.UnauthorizedRobotsPageLimit),
	}
}

func IsUnauthorizedRobotInList(robotId string) bool {
	urMu.RLock()
	defer urMu.RUnlock()

	for _, r := range unauthorizedRobots {
		if r.Id == robotId {
			return true
		}
	}

	return false
}

func GetUnauthorizedRobotById(robotId string) structs.UnauthorizedRobot {
	urMu.RLock()
	defer urMu.RUnlock()

	for _, r := range unauthorizedRobots {
		if r.Id == robotId {
			return *r
		}
	}

	return structs.UnauthorizedRobot{}
}

func RemoveUnauthorizedRobotById(robotId string) {
	urMu.Lock()
	defer urMu.Unlock()

	delete(unauthorizedRobots, robotId)
}
