package com.example.smart119.interfaces

import com.example.smart119.MyCookieJar
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import okhttp3.Cookie
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.net.ssl.*
import java.util.concurrent.TimeUnit

object RetrofitClient {
    private const val HOST_IP_TEST = "192.168.0.20"
    private const val HOST_PORT_TEST = "8080"
    private const val BASE_URL_HTTP_TEST = "http://${HOST_IP_TEST}:${HOST_PORT_TEST}"

    //#region 테스트용 ip


    //#region 일반 백엔드 api 설정
    private const val HOST_IP = "112.219.147.186"
    private const val HOST_PORT = "8085"
    private const val BASE_URL = "http://${HOST_IP}:${HOST_PORT}"
    //#endregion
    //#region nginx url 설정
    private const val NGINX_PORT = "1000"
    private const val NGINX_BASE_URL = "http://${HOST_IP}:${NGINX_PORT}"
    //#endregion
    //#endregion

    /*
    //#region 소방본부 서버용 ip
    //#region 일반 백엔드 api 설정
    private const val HOST_IP = "210.104.143.125"
    private const val HOST_PORT = "8085"
    private const val BASE_URL = "http://${HOST_IP}:${HOST_PORT}"
    //#endregion
    //#region nginx url 설정
    private const val NGINX_IP = "210.104.143.125"
    private const val NGINX_PORT = "1000"
    private const val NGINX_BASE_URL = "http://${NGINX_IP}:${NGINX_PORT}"
    //#endregion
    //http://210.104.143.125:8085/
    //#endregion
    */

    private const val BASE_URL_HTTP = "http://${HOST_IP}:${HOST_PORT}"
    private const val HTTP_URL_COOKIE = "http://192.168.0.20:3000"

    // 신뢰할 수 없는 인증서를 허용하는 OkHttpClient
    private fun getUnsafeOkHttpClient(): OkHttpClient {
        return try {
            val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {}
                override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {}
                override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> = arrayOf()
            })

            val sslContext = SSLContext.getInstance("TLS")
            sslContext.init(null, trustAllCerts, java.security.SecureRandom())
            val sslSocketFactory = sslContext.socketFactory

            OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
                .hostnameVerifier { _, _ -> true } // 모든 호스트 이름 허용
                .addInterceptor(CookieInterCeptor)
                .connectTimeout(10, TimeUnit.SECONDS) // 서버 연결 Timeout (기본 10초 → 30초)
                .readTimeout(10, TimeUnit.SECONDS)    // 서버 응답 Timeout (기본 10초 → 30초)
                .writeTimeout(10, TimeUnit.SECONDS)   // 서버 요청 Timeout (기본 10초 → 30초)
                .build()
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    private fun getUnsafeOkHttpClient_http(): OkHttpClient {
        return try {
            OkHttpClient.Builder()
                .addInterceptor(CookieInterCeptor)
                .connectTimeout(10, TimeUnit.SECONDS) // 서버 연결 Timeout (기본 10초 → 30초)
                .readTimeout(10, TimeUnit.SECONDS)    // 서버 응답 Timeout (기본 10초 → 30초)
                .writeTimeout(10, TimeUnit.SECONDS)   // 서버 요청 Timeout (기본 10초 → 30초)
                .build()
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    private val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
//            .client(getUnsafeOkHttpClient()) // 신뢰할 수 없는 인증서 허용 https
            .client(getUnsafeOkHttpClient_http())
            .addConverterFactory(GsonConverterFactory.create()) // Gson Converter 추가
            .build()
    }

    private val retrofit_NGINX: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(NGINX_BASE_URL)
            .client(getUnsafeOkHttpClient()) // 신뢰할 수 없는 인증서 허용
            .addConverterFactory(GsonConverterFactory.create()) // Gson Converter 추가
            .build()
    }

    private val retrofit_HTTP: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL_HTTP)
            .client(getUnsafeOkHttpClient()) // 신뢰할 수 없는 인증서 허용
            .addConverterFactory(GsonConverterFactory.create()) // Gson Converter 추가
            .build()
    }

    private val retrofit_HTTP_TEST: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL_HTTP_TEST)
            .client(getUnsafeOkHttpClient()) // 신뢰할 수 없는 인증서 허용
            .addConverterFactory(GsonConverterFactory.create()) // Gson Converter 추가
            .build()
    }

    //cookie 테스트용 retrofit
    private val retrofit_COOKIE: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(HTTP_URL_COOKIE)
            .client(getUnsafeOkHttpClient()) // 신뢰할 수 없는 인증서 허용
            .addConverterFactory(GsonConverterFactory.create()) // Gson Converter 추가
            .build()
    }

    val locInstance: apiLocation by lazy {
        retrofit.create(apiLocation::class.java)
    }

    val loginInstance: apiLogin by lazy {
        retrofit.create(apiLogin::class.java)
//        retrofit_HTTP.create(apiLogin::class.java)
//        retrofit_HTTP_TEST.create(apiLogin::class.java)
    }

    val transferInstance: apiTransfer by lazy {
        retrofit.create(apiTransfer::class.java)
//        retrofit_HTTP.create(apiTransfer::class.java)
//        retrofit_HTTP_TEST.create(apiTransfer::class.java)
    }

    val pathInstance: apiFindPath by lazy {
        retrofit_NGINX.create(apiFindPath::class.java)
    }

//    val cookieInstance: apiTransfer by lazy {
//        retrofit_COOKIE.create(apiTransfer::class.java)
//    }

    val hospitalInstance:apiHospital by lazy {
        retrofit.create(apiHospital::class.java)
    }

    fun parseJsonFromBuffer(buffer: ByteArray): JsonObject {
        val jsonString = buffer.toString(Charsets.UTF_8)
        val jsonElement = JsonParser.parseString(jsonString)
        return jsonElement.asJsonObject
    }

}
