package kr.lunaticbum.back.lun.controllers.view

import com.fasterxml.jackson.databind.ObjectMapper
import com.google.gson.Gson
import jakarta.servlet.http.HttpServletRequest
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.reactor.awaitSingleOrNull
import kr.lunaticbum.back.lun.configs.core.GlobalEnvironment
import kr.lunaticbum.back.lun.model.LocationLog
import kr.lunaticbum.back.lun.model.Post
import kr.lunaticbum.back.lun.model.ResponceResult
import kr.lunaticbum.back.lun.model.ResultMV
import kr.lunaticbum.back.lun.service.PostManager
import kr.lunaticbum.back.lun.services.LocationLogService
import kr.lunaticbum.back.lun.utils.LogService
import kr.lunaticbum.back.lun.utils.plainText
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/bums")
class BumsPrivate {
    @Autowired
    lateinit var globalEvv : GlobalEnvironment

    @Autowired
    lateinit var logService: LogService

    @Autowired
    lateinit var postManager : PostManager

    @Autowired
    lateinit var locationService: LocationLogService

    @GetMapping("face.bs")
    suspend fun aboutMePage(): ResultMV {
        val vm = ResultMV("content/about_view")
        val aboutPost = postManager.findLatestAboutPost().awaitSingleOrNull()

        if (aboutPost != null) {
            vm.modelMap["srcPost"] = aboutPost
            vm.modelMap["srcPostJson"] = ObjectMapper().writeValueAsString(aboutPost)
            vm.setTitle("BUM'sPace 소개")
        } else {
            vm.modelMap["srcPost"] = Post(title = "소개글이 아직 작성되지 않았습니다.", content = "")
            vm.modelMap["srcPostJson"] = "{}"
            vm.setTitle("소개글 없음")
        }
        return vm
    }

    @GetMapping("where.bs")
    suspend fun where(@RequestParam(value = "page", defaultValue = "0") page: Int) : ResultMV {
        val m = ResultMV("content/private/where")
        val pageable: Pageable = PageRequest.of(page, 30, Sort.by("time").descending())
        val locationPage  =  locationService.findAll(pageable).awaitSingle()
        m.modelMap.put("locationPage", locationPage)
        m.setTitle("돼지 여기있다요~!!")
        return m
    }

    @ResponseBody
    @PostMapping("save/loc.api")
    suspend fun login(httpServletRequest: HttpServletRequest, @RequestBody jsonString: String) : ResponseEntity<ResponceResult> {
        logService.log("${httpServletRequest.requestURI}")
        logService.log(jsonString)

        jsonString.plainText().let {
            Gson().fromJson<LocationLog>(it, LocationLog::class.java)?.let { model ->
                logService.log(model.toString())
                locationService.save(model).awaitSingle()
            }
        }
        val responce = ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponceResult().apply {
        })
        return responce
    }
}