/*
 * Copyright 2018 75py
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nagopy.android.textcounter

import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import com.github.salomonbrys.kodein.*
import com.github.salomonbrys.kodein.conf.ConfigurableKodein
import com.google.android.gms.ads.MobileAds
import com.nagopy.android.textcounter.counter.EnglishTextCounter
import com.nagopy.android.textcounter.counter.JapaneseTextCounter
import com.nagopy.android.textcounter.counter.TextCounters
import timber.log.Timber

class App : Application(), KodeinAware {

    override val kodein = ConfigurableKodein(mutable = true)

    override fun onCreate() {
        super.onCreate()

        resetInjection()

        if (BuildConfig.DEBUG) {
            Timber.plant(Timber.DebugTree())
        }

        MobileAds.initialize(this, BuildConfig.AD_APP_ID)
    }

    fun resetInjection() {
        kodein.clear()
        kodein.addImport(appModule(), true)
    }

    fun appModule() = Kodein.Module {
        bind<SharedPreferences>() with singleton { PreferenceManager.getDefaultSharedPreferences(this@App) }
        bind<TextBackup>() with singleton { TextBackup(instance()) }
        bind<Ads>() with singleton { Ads(instance()) }

        bind<TextCounters>() with singleton {
            TextCounters(instance(), instance(),
                    EnglishTextCounter(), JapaneseTextCounter())
        }
    }
}

fun Context.asApp() = this.applicationContext as App
