package gaf3.core.services.log

import gaf3.core.data.ErrorResult
import gaf3.core.data.PagedData
import gaf3.core.services.log.config.GafLogConfigure
import gaf3.core.services.log.domain.LogForm
import gaf3.core.services.log.domain.PageForm
import gaf3.core.services.log.domain.UpdateForm
import gaf3.core.services.log.entity.GafLog
import gaf3.core.services.log.service.LogService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.*
import javax.validation.Valid

@RestController("gafLogServiceController")
class LogServiceController(val service: LogService, val config: GafLogConfigure) {
    companion object {
        val log: Logger = LoggerFactory.getLogger(LogServiceController::class.java)
    }

    @GetMapping(path = ["/gaf/logs"])
    fun find(filter: GafLog, @RequestParam("timestamps[]") timestamps: Array<Long>? = null, skip: Int? = 0, limit: Int? = 100): PagedData<GafLog>{
        return service.find(filter = filter, timestamps = timestamps,
                skip = skip ?: 0, limit = limit ?: 100)
    }

    @GetMapping(path = ["/gaf/logs/{field}/values"])
    fun fetchValues(@PathVariable field: String): PagedData<String>{
        return service.fetchValues(field).let {
            PagedData(it, it.size)
        }
    }

    @PostMapping(path = ["/gaf/logs"])
    fun create(@Valid @RequestBody data: LogForm): GafLog {
        return service.create(data)
    }

    @PostMapping(path = ["/gaf/logs/{id}"])
    fun update(@PathVariable id: String, @RequestBody data: UpdateForm): ErrorResult {
        service.update(id, data)
        return ErrorResult(0,"updated")
    }

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

    @GetMapping(path = ["/gaf/logs/demo"])
    fun demo1(name: String): String {
        return "it is $name!"
    }

    @GetMapping(path = ["/gaf/logs/demo"], params = ["name=demo2"])
    fun demo2(name: String): String {
        return "I am $name!"
    }

    /**
     * 记录页面访问日志
     */
    @PostMapping(path = ["/gaf/logs/page"])
    fun page(@RequestBody data: PageForm): ErrorResult {
        log.info("[Log Page] {}", data.uri)
        return ErrorResult(0, "ok")
    }
}