package kr.lunaticbum.back.lun.controllers

import com.google.gson.Gson
import jakarta.servlet.http.HttpServletRequest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kr.lunaticbum.back.lun.configs.GlobalEnvironment
import kr.lunaticbum.back.lun.model.*
import kr.lunaticbum.back.lun.utils.LogService
import kr.lunaticbum.back.lun.utils.plainText
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.servlet.ModelAndView
import java.util.Base64


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

    @Autowired
    lateinit var logService: LogService

    @Autowired
    lateinit var locationService: LocationLogService

    @GetMapping("where.bs")
    fun where() : ResultMV {
        val m = ResultMV("content/private/where")

        locationService.find10().apply {
            m.modelMap.put("locations",this)
        }
        m.setTitle("돼지 여기있다요~!!")
        return m
    }

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

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

        })
//        CoroutineScope(Dispatchers.IO).launch {
//            location?.let {
//                val client = WebClient.create()
//                client.get()
//                    .uri("https://api.telegram.org/${globalEvv.telegramBotKey}/sendMessage?chat_id=${globalEvv.telegramMyId}&text=${it.mAddressLines.first()} 저장")
//                    .retrieve()
//                    .bodyToMono(String::class.java).block() ?: "FAIL"
//            }
//        }
        return responce
    }

}