package es.verdnatura

import android.app.Activity
import android.app.Application
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import es.verdnatura.dataStore.DataStoreLocal
import es.verdnatura.di.viewModelModule
import es.verdnatura.domain.ConstAndValues
import es.verdnatura.domain.RestClient
import es.verdnatura.domain.SalixService
import es.verdnatura.domain.toast
import es.verdnatura.presentation.common.InteceptorListener
import es.verdnatura.presentation.common.LoginListener
import es.verdnatura.presentation.common.MainActivityListener
import es.verdnatura.presentation.common.SignListener
import es.verdnatura.presentation.view.component.CustomDialogMainActivity
import es.verdnatura.presentation.view.feature.login.activity.LoginActivity
import kotlinx.coroutines.runBlocking
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.loadKoinModules
import org.koin.core.context.startKoin
import java.io.File

class MobileApplication : Application(), InteceptorListener {
    private lateinit var interceptoreListener: InteceptorListener
    private var mainActivityListener: MainActivityListener? = null
    private var loginListener: LoginListener? = null
    private var signListener: SignListener? = null
    private var isActivityLoginRunning = false

    fun setMainListener(listener: MainActivityListener) {
        mainActivityListener = listener
    }

    fun setLoginListener(listener: LoginListener) {
        loginListener = listener
    }

    fun setSignListener(listener: SignListener) {
        signListener = listener
    }

    // lateinit var silex: VerdnaturaService
    lateinit var salix: SalixService
    var userId: Int? = null
    var userName: String? = null
    var renewPeriod: Long = 0
    var renewInterval: Long = 0
    var userPassword: String? = null
    var hasNetwork: Boolean = true
    var serialNumber: String? = ""
    var versionName: String = ""
    var androidId: String = ""
    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null
    var dataStoreApp = DataStoreLocal(this)
    private lateinit var customDialog: CustomDialogMainActivity
    private val handler = Handler(Looper.getMainLooper())

    override fun onCreate() {
        super.onCreate()
        mperror = MediaPlayer.create((this), R.raw.error)
        mpok = MediaPlayer.create((this), R.raw.ok)
        startKoin {
            androidContext(this@MobileApplication)
            val moduleList = listOf(viewModelModule)
            loadKoinModules(moduleList)
        }


        runBlocking {
            dataStoreApp.editDataStoreKey(
                ConstAndValues.BASEURLSALIX, ConstAndValues.BASE_URL_SALIX
            )
        }
        val restClient = RestClient(this, this)
        salix = restClient.salixClient

        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            }

            override fun onActivityStarted(activity: Activity) {
            }

            override fun onActivityResumed(activity: Activity) {
                isActivityLoginRunning = activity.javaClass == LoginActivity::class.java
            }

            override fun onActivityPaused(activity: Activity) {
                if (activity.javaClass == LoginActivity::class.java) {
                    isActivityLoginRunning = false
                }
            }

            override fun onActivityStopped(activity: Activity) {
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
                isActivityLoginRunning = false
            }
        })

    }

    fun messageToast(isError: Boolean, message: String, isToasted: Boolean = false) {
        when (isError) {
            false -> mpok
            true -> mperror
        }?.start()

        if (isToasted) message.toast(
            this, color = if (isError) {
                Color.RED
            } else {
                Color.BLUE
            }
        )
    }

    fun isLoginRunning(): Boolean {
        return isActivityLoginRunning
    }

    override fun onInterceptionResult(visibility: Int) {
        if (mainActivityListener != null) {
            handler.post {
                (this.mainActivityListener)?.onApplicationEventAnimation(visibility)
            }
        }
        if (loginListener != null) {
            handler.post {
                (this.loginListener)?.onApplicationEventAnimation(visibility)
            }
        }
        if (signListener != null) {
            handler.post {
                (this.signListener)?.onApplicationEventAnimation(visibility)
            }
        }
    }

    fun getLanguage(): String {
        val settings = this.resources.configuration
        return settings.locales.get(0).language
    }

    fun clearApplicationData() {
        try {
            val cacheDir = this.cacheDir
            val appDir = File(cacheDir.parent ?: return)
            if (appDir.exists()) {
                val children = appDir.list() ?: return
                for (child in children) {
                    if (child != "lib") {
                        deleteDir(File(appDir, child))
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun deleteDir(dir: File): Boolean {
        if (dir.isDirectory) {
            val children = dir.list() ?: return false
            for (child in children) {
                val success = deleteDir(File(dir, child))
                if (!success) {
                    return false
                }
            }
        }
        return dir.delete()
    }

}