package com.framework.di

import android.content.Context
import com.framework.app.IP
import com.framework.app.api.Api
import com.framework.app.converter.NullOrEmptyConverter
import com.framework.app.http.GzipRequestInterceptor
import com.framework.mvvm.model.db.AdmDatabase
import com.framework.mvvm.model.repository.AdmRepository
import com.framework.mvvm.mv.AdmViewModel
import com.sybotan.android.demo.tools.LogUtil
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.kodein.di.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.UnsupportedEncodingException
import java.util.concurrent.TimeUnit


val httpModule = DI.Module("netModule") {
    // 构建 Retrofit 对象

    bind {
        singleton {
            Retrofit.Builder()
                .baseUrl(IP)
                .client(instance())
                .addConverterFactory(NullOrEmptyConverter())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
    }

    // 构建 OkHttpClient 对象
    bind {
        singleton {
            OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(300, TimeUnit.SECONDS)
                .writeTimeout(300, TimeUnit.SECONDS)
                .addInterceptor(instance<GzipRequestInterceptor>())
                .addInterceptor(instance<HttpLoggingInterceptor>())
                .build()
        }
    }

    // 构建 HttpLoggingInterceptor 对象
    bind {
        singleton {
            HttpLoggingInterceptor { message ->
                try {
                    LogUtil.e("OKHttp-----", message)
                } catch (e: UnsupportedEncodingException) {
                    e.printStackTrace()
                    LogUtil.e("OKHttp-----", message)
                }
            }.setLevel(HttpLoggingInterceptor.Level.BODY)
        }
    }

    bind {
        singleton {
            GzipRequestInterceptor()
        }
    }

    // Api 对象
    bind {
        singleton { instance<Retrofit>().create(Api::class.java) }
    }
}

val repositoryModule = DI.Module("repository") {
    bindSingleton { AdmRepository(instance(), instance(), instance()) }
}

val viewModelModule = DI.Module("viewModel") {
    bindProvider { AdmViewModel(instance()) }
}

val androidModule = DI.Module("sys") {
    bindSingleton {
        instance<Context>().getSharedPreferences(
            "adm_sp",
            Context.MODE_PRIVATE
        )
    }
}
val databaseModule = DI.Module("database") {
    bindSingleton {
        AdmDatabase.getDatabase(instance())
    }
}