package kr.lunaticbum.back.lun.configs

import com.google.gson.Gson
import jakarta.servlet.http.Cookie
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import kr.lunaticbum.back.lun.configs.GlobalEnvironment.Companion.ApiKeyWordKey
import kr.lunaticbum.back.lun.configs.GlobalEnvironment.Companion.EncType11
import kr.lunaticbum.back.lun.configs.GlobalEnvironment.Companion.EncTypeKey
import kr.lunaticbum.back.lun.model.UserManager
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.lang.Nullable
import org.springframework.security.web.authentication.RememberMeServices
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.ModelAndView

@Component
class BumsInterceptor : HandlerInterceptor {

    @Autowired
    lateinit var globalEvv : GlobalEnvironment

    val WRITE_PERMISSION_KEY = "PERMISSION"

    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        var skippResourcesExtension = arrayListOf(".js",".css").filter { request.requestURI.contains(it) }.size > 0
//        if (!skippResourcesExtension) {
//            println("===============================================")
//            println("==================== BEGIN ====================")
//            println("Request URL ===> " + request.requestURL)
//        }


        return super.preHandle(request, response, handler)
    }

//    @Autowired
//    lateinit var rememberMeServices: RememberMeServices

    @Throws(Exception::class)
    override fun postHandle(
        request: HttpServletRequest,
        response: HttpServletResponse,
        handler: Any,
        @Nullable modelAndView: ModelAndView?
    ) {
//        if(remeberMe && authResult != null) {
//            rememberMeServices.loginSuccess(httpServletRequest, responce, authResult)
//        }

        modelAndView?.modelMap?.put(EncTypeKey, EncType11)
        modelAndView?.modelMap?.put(ApiKeyWordKey,"Def")
        if (modelAndView != null) {
            modelAndView.modelMap.put(EncTypeKey, EncType11)
            modelAndView.modelMap.put(ApiKeyWordKey, "Def")
            println("modelMap 내용 추가 완료: ${modelAndView.modelMap}")
        } else {

            println("modelAndView가 null이라 모델에 값 추가 불가")
        }

        super.postHandle(request, response, handler, modelAndView)
    }

    fun cookieUpdate(cookie: Cookie?) : Cookie? {
        cookie?.maxAge = (globalEvv.ACCESS_EXPIRATION / 1000).toInt()
        cookie?.domain = "lunaticbum.kr"
        cookie?.secure = true
        cookie?.path = "/"
        return cookie
    }
}