package gaf3.core.services.code

import gaf3.core.data.ErrorResult
import gaf3.core.data.JsonResult
import gaf3.core.data.PagedData
import gaf3.core.services.code.domain.CodeForm
import gaf3.core.services.code.domain.CodeItem
import gaf3.core.services.code.service.CodeService
import org.springframework.web.bind.annotation.*
import javax.validation.Valid

@RestController
class CodeServiceController(val service: CodeService) {
//    companion object {
//        val log: Logger = LoggerFactory.getLogger(UserServiceController::class.java)
//    }

    @PostMapping(path = ["/gaf/code/types"])
    fun createType(@Valid @RequestBody data: CodeForm): JsonResult<CodeItem> {
        val res = service.create("group", data)
        return JsonResult(res)
    }

    @GetMapping(path = ["/gaf/code/types"])
    fun listTypes(): PagedData<CodeItem> {
        val rs = service.listTypes()
        return PagedData(rs, rs.size)
    }

//    @GetMapping(path = ["/gaf/code/{type}/items"])
//    fun listCodes(@PathVariable type: String): PagedData<CodeItem>{
//        return service.listCodes(type)
//    }

    @GetMapping(path = ["/gaf/code/items"])
    fun findItems(filter: CodeItem, skip: Int? = 0, limit: Int? = 100): PagedData<CodeItem>{
        return service.find(filter, skip ?: 0, limit ?: 100)
    }

    @PostMapping(path = ["/gaf/code/items"])
    fun create(@RequestParam type: String?, @Valid @RequestBody data: CodeForm): CodeItem {
        return service.create(type, data)
    }

    @DeleteMapping(path = ["/gaf/code/items/{id}"])
    fun delete(@PathVariable id: String): ErrorResult {
        service.delete(id)
        return ErrorResult(0,"deleted")
    }

    @PostMapping(path = ["/gaf/code/items/{id}"])
    fun update(@PathVariable id: String, @RequestBody data: CodeForm): CodeItem{
        return service.update(id, data)
    }

    @GetMapping(path = ["/gaf/code/items/{id}"])
    fun fetch(@PathVariable id: String): CodeItem? {
        return service.fetch(id)
    }

    @GetMapping(path = ["/gaf/code/{type}/{code}"])
    fun fetchByCode(@PathVariable type: String, @PathVariable code: String): CodeItem?{
        val filter = CodeItem(type = type, code = code)
        val rs = service.find(filter, 0, 1)
        return if(rs.total > 0){
            rs.data!![0]
        } else {
            null
        }
    }
}