package inn.ocsf.bee.freigeld.serve.rest

import inn.ocsf.bee.freigeld.core.model.PersonalizedId
import inn.ocsf.bee.freigeld.serve.PersonService
import inn.ocsf.bee.freigeld.utils.KeyValueBucket.personToLabel
import inn.ocsf.bee.freigeld.utils.KeyValueStorage
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.util.*
import javax.inject.Inject

@RestController
class PersonOptsController {

    @Inject
    private lateinit var kvStore: KeyValueStorage

    @Inject
    private lateinit var personService: PersonService

    @RequestMapping("api/old/person/{personId}/opts/label/{labelId}", method = [RequestMethod.GET])
    fun getLabel(@PathVariable("personId") personId: UUID, @PathVariable("labelId") labelId: String): ResponseEntity<LabelResp?> {
        if (personId != personService.getCurrentPerson()?.id) throw IllegalAccessException("wrong person")
        val lv = kvStore.get<String>(personToLabel, PersonalizedId(personId, labelId))?.let { LabelResp(labelId, it) }
        return ResponseEntity.ok(lv)
    }

    @RequestMapping("api/old/person/{personId}/opts/label/{labelId}", method = [RequestMethod.POST])
    fun putLabel(@PathVariable("personId") personId: UUID, @PathVariable("labelId") labelId: String, @RequestBody req: LabelReq): ResponseEntity<LabelResp?> {
        if (personId != personService.getCurrentPerson()?.id) throw IllegalAccessException("wrong person")
        if (req.label != null) {
            kvStore.put(personToLabel, PersonalizedId(personId, labelId), req.label)
        } else {
            kvStore.remove(personToLabel, PersonalizedId(personId, labelId))
        }
        return getLabel(personId, labelId)
    }

}

data class LabelReq(val label: String?)

data class LabelResp(val labelId: String, val label: String)