package app.furmeet.events.system

import android.content.Context
import android.content.res.Configuration
import android.view.MenuItem
import androidx.annotation.CallSuper
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import app.furmeet.events.system.helper.LocaleManager
import app.furmeet.events.system.schedule.managers.RemoteAssetsHolder
import app.furmeet.events.bff.R

abstract class TranslatableAppCompatActivity: AppCompatActivity() {
    override fun attachBaseContext(baseContext: Context) {
        super.attachBaseContext(LocaleManager(baseContext).patchedContext)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        newConfig.setLocale(LocaleManager(this).locale)
        super.onConfigurationChanged(newConfig)
    }

    @CallSuper
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_toggle_night_day_mode -> {
                isDarkMode = !isDarkMode
                applySavedNightMode()
                true
            }
            android.R.id.home -> {
                finish()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private var isDarkMode
        get() = getSharedPreferences(
            RemoteAssetsHolder.remoteAssets.project,
            MODE_PRIVATE
        ).getBoolean("isDarkModeOn", false)
        set(value) =
            getSharedPreferences(
                RemoteAssetsHolder.remoteAssets.project,
                MODE_PRIVATE
            ).edit().putBoolean("isDarkModeOn", value).apply()

    private fun applySavedNightMode() =
        AppCompatDelegate.setDefaultNightMode(if (isDarkMode) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO)

    @CallSuper
    override fun onStart() {
        super.onStart()
        applySavedNightMode()
    }
}