package com.feasycom.feasybeacon

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import cat.ereza.customactivityoncrash.config.CaocConfig
import com.feasycom.feasybeacon.logic.dao.DeviceDatabase
import com.feasycom.feasybeacon.logic.model.*
import com.feasycom.feasybeacon.logic.utils.getStr
import com.feasycom.feasybeacon.ui.CrashActivity
import com.feasycom.feasybeacon.ui.MainActivity
import com.feasycom.feasybeacon.ui.utils.BeaconDataManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class App : Application() {

    override fun onCreate() {
        super.onCreate()
        sContext = applicationContext
        val storedHash = getStr("hash", "")
        MainScope().launch(Dispatchers.IO) {
            BeaconDataManager.fetchAndStoreBeaconData(sContext, storedHash, mBeaconItemDao)
        }
        configureCrashHandling()
    }

    private fun configureCrashHandling() {
        CaocConfig.Builder.create().apply {
            backgroundMode(CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM)
            enabled(true)
            trackActivities(true)
            minTimeBetweenCrashesMs(2000)
            restartActivity(MainActivity::class.java)
            errorActivity(CrashActivity::class.java)
        }.apply()
    }

    companion object {
        const val TAG = "BeaconAPP"
        @SuppressLint("StaticFieldLeak")
        lateinit var sContext: Context
        val mBeaconItemDao by lazy {
            DeviceDatabase.getDatabase(sContext).deviceDao()
        }
    }

}