package com.sd.cavphmi.moudule


import com.sd.cavphmi.net.HeadParamsInterceptor
import com.sd.cavphmi.net.RetrofitApi
import com.sd.cavphmi.net.RetrofitApi.retrofitBuild
import com.sd.cavphmi.net.httpmothod.ClientRetrofitMethod
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.security.KeyStore
import java.util.*
import javax.inject.Qualifier
import javax.inject.Singleton
import javax.net.ssl.*

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class OriginOkHttpClient

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class AuthInterceptorOkHttpClient

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class NormalInterceptorOkHttpClient


@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    var logging = HttpLoggingInterceptor()

    init {
        logging.level = HttpLoggingInterceptor.Level.BODY
    }


    @OriginOkHttpClient
    @Provides
    fun provideOriginOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(logging)
            .build()
    }

    @NormalInterceptorOkHttpClient
    @Provides
    fun provideNormalInterceptorOkHttpClient(
        headParamsInterceptor: HeadParamsInterceptor,
    ): OkHttpClient {
        return OkHttpClient.Builder()
            .cache(RetrofitApi.cache)
            .addInterceptor(headParamsInterceptor)
            .hostnameVerifier { hostname, session -> true }
            .addInterceptor(logging)
            .build()
    }

    //------------------API  方法---------------
    @Singleton
    @Provides
    fun provideClientRetrofitService(@NormalInterceptorOkHttpClient okHttpClient: OkHttpClient): ClientRetrofitMethod {
        return retrofitBuild.client(okHttpClient).build().create(ClientRetrofitMethod::class.java)
    }


    fun getSSlSocketFactory(): SslData {
        val trustManagerFactory: TrustManagerFactory = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm()
        )
        trustManagerFactory.init(null as KeyStore?)
        val trustManagers: Array<TrustManager> = trustManagerFactory.getTrustManagers()
        check(!(trustManagers.size != 1 || trustManagers[0] !is X509TrustManager)) {
            ("Unexpected default trust managers:"
                    + Arrays.toString(trustManagers))
        }
        val trustManager = trustManagers[0] as X509TrustManager


        val sslContext = SSLContext.getInstance("TLS")
        sslContext.init(null, arrayOf<TrustManager>(trustManager), null)
        val sslSocketFactory = sslContext.socketFactory

        return SslData(sslSocketFactory, trustManager)
    }

    data class SslData(val sslSocketFactory: SSLSocketFactory, var trustManager: X509TrustManager)

}