/*
 * ********************************************************************************************************************
 *
 *                      :*$@@%$*:                         ;:                ;;    ;;
 *                    :@@%!  :!@@%:                       %!             ;%%@@%$ =@@@@@@@%;     @%@@@%%%%@@@@@
 *                   :@%;       :$=                       %%$$$%$$         ;$$  ;$@=   !@$
 *                   =@!                                  %!              @ $=;%   !@@@%:      !$$$$$$$$$$$$$$=
 *                   =@*                                  %!              @ $= % %@=   =%@!      %=
 *              *$%%! @@=        ;=$%%%$*:                %!              @ $= % =%%%%%%@$      *%:         =%
 *            %@@!:    !@@@%=$@@@@%!  :*@@$:              %!              @ $= % $*     ;@      @*          :%*
 *          ;@@!          ;!!!;:         ;@%:      =======@%========*     @ $$ % $%*****$@     :@$=*********=@$
 *          $@*   ;@@@%=!:                *@*
 *          =@$    ;;;!=%@@@@=!           =@!
 *           %@$:      =@%: :*@@@*       %@=                    Copyright (c) 2016-2019.  北京上格云技术有限公司
 *            ;%@@$=$@@%*       *@@@$=%@@%;
 *               ::;::             ::;::                                              All rights reserved.
 *
 * ********************************************************************************************************************
 */

package com.persagy.server.sso.interceptors

//import org.apache.shiro.SecurityUtils
//import org.apache.shiro.authc.UsernamePasswordToken
//import org.apache.shiro.subject.Subject
import org.slf4j.LoggerFactory
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class SessionInterceptor : HandlerInterceptorAdapter() {
    companion object {
        // 日志
        private val logger = LoggerFactory.getLogger(SessionInterceptor::class.java)
    } // Companion object

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        println("URL=${request.requestURI.toString()}")
        if (request.requestURI.indexOf("swagger-") > 0 ||
                request.requestURI.endsWith(".png") ||
                request.requestURI.endsWith(".jpg")
                ) {
            return super.preHandle(request, response, handler)
        }

        val token = request.getHeader("sso-token")
        //val token = request.getParameter("token")

        logger.debug("sso-token=$token")
        if (token == null) {
            response.writer.write("{\"result\":\"unauthc\",\"message\":\"no token\"}")
            //writeJson(response, "{\"result\":\"unauthc\",\"message\":\"no token\"}")
            return false
        }

        try {
//            val subject = SecurityUtils.getSubject()
//            if (subject.isAuthenticated) {
//                try {
//                    val user = subject.principal as User
////                    if (!userModel.getToken().equalsIgnoreCase(token)) {
////                        return checkToken(subject, token, response)
//////                    }
//                } catch (e1: Exception) {
//                    return checkToken(subject, token, response)
//                }
//            } else {
//                return checkToken(subject, token, response)
//            }
        } catch (e: Exception) {
            e.printStackTrace()
            logger.error("login check error: {}", e)
            return false
        }

        return true
    } // Function preHandle()

//    private fun checkToken(subject: Subject, token: String, response: HttpServletResponse): Boolean {
//        val resp = SSoClient.tokenCheck(token)
//        logger.info("token check resp: ${resp.toJson()}")
//        if (resp.result != "success") {
//            logger.error("go to login")
//            response.writer.write(resp.toJson())
//            //writeJson(response, resp.toJson())
//            return false
//        }
//
//        val userId = resp.id
//        val user: User? = User()
//        user?.id = resp.id
//        user?.userName = resp.userName
//
//        if (user == null) {
//            // 用户不存在
//            val r = BaseResponse("")
//            response.writer.write("{\"result\": \"nouser\"}")
//            //writeJson(response, "{\"result\": \"nouser\"}")
//            return false
//        } else {
//            logger.error("=================================================================")
//            SPageContext.setAttribute("User", resp)
//            val user = SPageContext.getAttribute("User") as TokenCheckResponse?
//            logger.error("user = ${user?.toJson()}")
//            val token = UsernamePasswordToken(resp.id, "password")
//            subject.login(token)
//        }
//        return true
//    } // Function checkToken()


//    fun writeJson(response: HttpServletResponse, json: String) {
//        response.contentType = "application/json;charset=UTF-8"
//        var out: PrintWriter? = null
//        try {
//            out = response.writer
//            out!!.print(json)
//            out.flush()
//        } catch (e: IOException) {
//            e.printStackTrace()
//        } finally {
//            out?.close()
//        }
//    }
} // Class SessionInterceptor
