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.model.UserManager
import kr.lunaticbum.back.lun.service.JwtService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.lang.Nullable
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 jwtService : JwtService
    @Autowired
    lateinit var globalEvv : GlobalEnvironment
    @Autowired
    lateinit var userManager: UserManager

    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)
    }


    @Throws(Exception::class)
    override fun postHandle(
        request: HttpServletRequest,
        response: HttpServletResponse,
        handler: Any,
        @Nullable modelAndView: ModelAndView?
    ) {
        var skippResourcesExtension = arrayListOf(".ajax",".js",".css","/tlg/").filter { request.requestURI.contains(it)}.size > 0
        if (!skippResourcesExtension) {
            if (request.requestURI.contains("logout") == false && !request.cookies.isNullOrEmpty() && request.cookies.filter {
                    it.name.equals(
                        "access"
                    ) && it.value.length > 0
                }.size > 0) {
                var refreshOk = false;
                var accessOk = false;
                var access: Cookie? = null
                var refresh: Cookie? = null
                request.cookies.forEach {
                    if (it.name.equals("access", true) && jwtService.validateAccessToken(it.value)) {
                        access = it
                        accessOk = true
                        println("==================== accessOk ${accessOk} ======================")

                    }
                }
                request.cookies.forEach {
                    if (it.name.equals("refresh", true) && jwtService.validateRefreshToken(access?.value, it.value)) {
                        refresh = it
                        refreshOk = true
                        println("==================== refreshOk ${refreshOk} ======================")
                    }
                }
                if (refreshOk || accessOk) {
                    request.getSession(true)?.let { session ->
                        session.setAttribute(WRITE_PERMISSION_KEY, true)
                        session.maxInactiveInterval = 60 * 5
                    }
                } else {

                }
            } else if (request.requestURI.contains("logout")) {
                request.getSession(true)?.let { session ->
                    session.invalidate()
                    session.setAttribute(WRITE_PERMISSION_KEY, false)
                }
            }

            request.cookies?.forEach {
                if (it.name.equals("CLEAR", true)) {
                    request.getSession(true)?.let { session ->
                        session.invalidate()
                        session.setAttribute(WRITE_PERMISSION_KEY, false)
                    }
                }
            }
            modelAndView?.modelMap?.put(WRITE_PERMISSION_KEY,"NO")
            request.getSession(true)?.let {
                (it.getAttribute(WRITE_PERMISSION_KEY) as? Boolean)?.let { permission ->
                    if (permission) {
                        modelAndView?.modelMap?.put(WRITE_PERMISSION_KEY,"OK")
                    }
                }
            }
            println("==================== END ======================")
            println("===============================================")
        }
        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
    }
}