package gaf3.core.services.user

import gaf3.core.data.ErrorResult
import gaf3.core.data.JsonResult
import gaf3.core.data.PageParam
import gaf3.core.data.PagedData
import gaf3.core.exception.BusinessError
import gaf3.core.services.user.domain.*
import gaf3.core.services.user.service.UserService
import org.springframework.web.bind.annotation.*
import javax.validation.Valid

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

    @PostMapping("/gaf/users")
    fun create(@Valid @RequestBody data: CreateForm) : UserInfo {
        return service.create(data)
    }

    @GetMapping("/gaf/users")
    fun query(filter: UserInfo, paging: PageParam) : PagedData<UserInfo> {
        return service.find(filter, paging)
    }

    @GetMapping("/gaf/users/{userId}")
    fun fetch(@PathVariable userId: String) : UserInfo {
        return service.fetch(userId) ?: throw BusinessError(BusinessError.ERR_DATA_NOTEXIST)
    }

    @DeleteMapping("/gaf/users/{userId}")
    fun delete(@PathVariable userId: String) : ErrorResult {
        service.delete(userId)
        return ErrorResult(0,"deleted")
    }

    @PostMapping("/gaf/users/{userId}")
    fun update(@PathVariable userId: String, @Valid @RequestBody data: UpdateForm) : UserInfo {
        return service.update(userId, data)
    }

    @PostMapping("/gaf/users/{userId}/acct")
    fun updateAccount(@PathVariable userId: String, @RequestBody data: AcctForm) : ErrorResult {
        service.updateAcct(userId, data)
        return ErrorResult(0, "updated")
    }

    @PostMapping("/gaf/users/passwd")
    fun changePass(@RequestParam(name = "userId", required = true) userId: String?, @Valid @RequestBody data: PassForm) : ErrorResult {
        service.changePass(userId ?: "none", data.oldpass!!, data.newpass!!)
        return ErrorResult(0, "updated")
    }

    @PostMapping("/gaf/users/login")
    fun login(@PathVariable userId: String, @Valid @RequestBody data: LoginForm) : JsonResult<UserInfo> {
        val res = service.login(data.account!!, data.password!!)
        return JsonResult(res)
    }

}