package cache

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

/*
This stores the inputs that a user makes when typing into the input fields at a Group Task step.
This storage is necessary so that other users when opening this GroupTask or reloading the browser receive the data entered by the other user.
*/
var groupTaskStepsInputs []structs.GroupTaskStepsInput
var gtsi sync.RWMutex

func AddGroupTaskStepsInput(groupTaskStepsInput structs.GroupTaskStepsInput) {
	gtsi.Lock()

	var isAlreadyInList bool

	for i, input := range groupTaskStepsInputs {
		if input.GroupTaskId == groupTaskStepsInput.GroupTaskId && input.Step == groupTaskStepsInput.Step && input.ParameterName == groupTaskStepsInput.ParameterName {
			isAlreadyInList = true
			groupTaskStepsInputs[i].Value = groupTaskStepsInput.Value
			break
		}
	}

	if !isAlreadyInList {
		groupTaskStepsInputs = append(groupTaskStepsInputs, groupTaskStepsInput)
	}

	gtsi.Unlock()
}

func GetGroupTaskStepsInputs() []structs.GroupTaskStepsInput {
	gtsi.RLock()
	defer gtsi.RUnlock()

	return groupTaskStepsInputs
}

type InputParameters struct {
	ParameterName string      `json:"parameterName"`
	Value         interface{} `json:"value"`
}

func GetGroupTaskStepsInputsValue(inputs []structs.GroupTaskStepsInput, groupTaskId string, step uint8) string {
	var inputParameters []InputParameters

	for _, input := range inputs {
		if input.GroupTaskId == groupTaskId && input.Step == step {
			inputParameters = append(inputParameters, InputParameters{
				ParameterName: input.ParameterName,
				Value:         input.Value,
			})
		}
	}

	if len(inputParameters) == 0 {
		return ""
	}

	return utils.MarshalJson(inputParameters)
}
