package com.ys.bdtp.adm.di

import android.util.Log
import com.ys.bdtp.adm.app.IP
import com.ys.bdtp.adm.app.converter.NullOrEmptyConverter
import com.ys.bdtp.adm.app.interceptor.GzipRequestInterceptor
import com.ys.bdtp.adm.mvvm.model.db.AdmDatabase
import com.ys.bdtp.adm.mvvm.model.nt.Api
import com.ys.bdtp.adm.mvvm.vm.flash.FlashRepository
import com.ys.bdtp.adm.mvvm.vm.flash.FlashViewModel
import com.ys.bdtp.adm.mvvm.vm.login.LoginRepository
import com.ys.bdtp.adm.mvvm.vm.login.LoginViewModel
import com.ys.bdtp.adm.mvvm.vm.main.MainRepository
import com.ys.bdtp.adm.mvvm.vm.main.MainViewModel
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("httpModule") {
    // 构建 Retrofit 对象
    bind {
        singleton {
            Retrofit.Builder()
                .baseUrl(IP)
                .client(instance())
                .addConverterFactory(NullOrEmptyConverter())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
    }

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

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

    bind {
        singleton {
            GzipRequestInterceptor()
        }
    }

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

val repositoryModule = DI.Module("repository") {
    bind { provider { FlashRepository(instance(), instance()) } }
    bind { provider { LoginRepository(instance(), instance()) } }
    bind { provider { MainRepository(instance()) } }
}

val viewModelModule = DI.Module("viewModel") {
    bind { provider { FlashViewModel(instance()) } }
    bind { provider { LoginViewModel(instance()) } }
    bind { provider { MainViewModel(instance()) } }
}

val dbModule = DI.Module("dbModule") {
    bind {
        singleton {
            AdmDatabase(instance())
        }
    }
}