package com.sambath.kunkhmer.app

import android.app.Application
import android.content.Context
import android.util.Log
import com.itkacher.okhttpprofiler.OkHttpProfilerInterceptor
import com.sambath.kunkhmer.config.Config
import com.sambath.kunkhmer.BuildConfig
import com.sambath.kunkhmer.remote.service.ApiService
import com.sambath.kunkhmer.remote.service.SocketService
import com.sambath.kunkhmer.util.*
import com.squareup.moshi.Moshi
import com.squareup.picasso.Picasso
import okhttp3.OkHttpClient
import retrofit2.CallAdapter
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import timber.log.Timber
import java.util.concurrent.TimeUnit

class App : Application() {
    companion object {
        private lateinit var retrofit: Retrofit
        private lateinit var apiService: ApiService
        private lateinit var socketService: SocketService
        private lateinit var picasso: Picasso
        private lateinit var shareViewModel: ShareViewModel
        private lateinit var prefHelper: PrefHelper
        var guidelineLeft: Float = 0f
        var guidelineRight: Float = 100f
        fun injectApiService() = apiService
        fun injectShareViewModel() = shareViewModel
        fun injectPrefHelper() = prefHelper
        // Called on main activity create
        fun onStartSocket(token: String, channelType: Int) {
            Log.d("Socket", "token :: "+ token)
            shareViewModel.startListenSocket(token, channelType)
        }
        // Called on main activity destroy
        fun onAppStop() {
            //Log.d("Socket", "onAppStop")
            shareViewModel.stopListeningToSocketServer()
        }
    }

    override fun onCreate() {
        super.onCreate()
        ModelPreferencesManager.with(this)
        picasso = Picasso.Builder(this).loggingEnabled(true).build()
        // FirebaseApp.initializeApp(this)
        Picasso.setSingletonInstance(picasso)
        if (BuildConfig.DEBUG) {
            Timber.uprootAll()
            Timber.plant(Timber.DebugTree())
        }
        val widthPx = screenRectPx.width()
        val heightPx = screenRectPx.height()
        val percentage = widthPx * 100 / heightPx
        // Log.d("DATA", ""+widthPx)
        // Log.d("DATA", ""+heightPx)
        //  Log.d("DATA", ""+percentage)
        when (percentage) {
            in 30..54 -> {
                guidelineLeft = 0f
                guidelineRight = 1f
            }
            else -> {
                guidelineLeft = 0.05f
                guidelineRight = 0.95f
            }
        }
        prefHelper = PrefHelper(context = appContext(this))
        val builder = OkHttpClient.Builder()
        if (BuildConfig.DEBUG) {
            builder
                .addInterceptor(ServiceInterceptor(prefHelper))
                .addInterceptor(OkHttpProfilerInterceptor())
                .addInterceptor(ErrorInterceptor(appContext(this), prefHelper))
                .connectTimeout(180, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.MINUTES)
                .writeTimeout(180, TimeUnit.SECONDS)

        } else {
            builder
                .addInterceptor(ServiceInterceptor(prefHelper))
                .addInterceptor(ErrorInterceptor(appContext(this), prefHelper))
                .connectTimeout(180, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.MINUTES)
                .writeTimeout(180, TimeUnit.SECONDS)
        }
        val client = builder.build()
        retrofit = Retrofit.Builder()
            .baseUrl(Config.BASE_URL)
            .client(client)
            .addCallAdapterFactory(callFactory())
            .addConverterFactory(converterFactory(moshi()))
            .build()
        apiService = retrofit.create(ApiService::class.java)
        socketService = SocketService()
        //loginViewModel = LoginViewModel(apiService, prefHelper)
        //settingViewModel = SettingViewModel(apiService, prefHelper)
        shareViewModel = ShareViewModel(apiService, prefHelper, socketService)
    }

    private fun  callFactory(): CallAdapter.Factory = RxJava2CallAdapterFactory.create()
    private fun converterFactory(moshi: Moshi): Converter.Factory =
        MoshiConverterFactory.create(moshi).withNullSerialization()

    private fun moshi(): Moshi = Moshi.Builder().build()

    //fun unSafeOkHttpClient(): OkHttpClient = UnsafeOkHttpClient.getClient()
    private fun appContext(app: App): Context = app
    fun unSafeOkHttpClient(): OkHttpClient = UnsafeOkHttpClient.getClient()
}
