package com.quiescent.wallpaper.collection.test

import android.app.Application
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.applovin.sdk.AppLovinSdk
import com.applovin.sdk.AppLovinSdkInitializationConfiguration
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.quiescent.wallpaper.collection.test.bean.Info
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.StringWriter

class WallpaperCollection : Application() {

    var list: MutableList<Info> = mutableListOf()

    companion object {
        const val MAX_SDK_CODE = "VNL26CMGzXqLLfS5kMl2Nmz51a6LsHeLK3piaHf4dtiplx5ludvxFe6tU9hdhFWJEPLgH7QyzOpbXT056xw_Bi"
        const val MAX_PROVIDER = "max"
        const val INIT_SUCCESS_ACTION = "init_success_action"
        var INIT_SUCCESS = false
        lateinit var instance: WallpaperCollection
    }

    private fun getJsonString(fileInputStream: InputStream): String {
        return try {
            val charArray = CharArray(fileInputStream.available())
            var readCount = 0
            val streamReader =
                InputStreamReader(fileInputStream)
            val bufferedReader = BufferedReader(streamReader)
            val stringWriter = StringWriter()
            while (bufferedReader.read(charArray).also { readCount = it } != -1) {
                stringWriter.write(charArray, 0, readCount)
            }
            stringWriter.toString()
        } catch (e: IOException) {
            ""
        }
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        initMaxInter()
        val open = assets.open("wallpaper.json")
        val jsonStr = getJsonString(open)
        list = Gson().fromJson(jsonStr, object : TypeToken<List<Info>>() {}.type)

    }

    private fun initMaxInter() {
        val localBroadcastManager = LocalBroadcastManager.getInstance(this)
        AppLovinSdk.getInstance(this)
            .initialize(
                AppLovinSdkInitializationConfiguration.builder(MAX_SDK_CODE, this)
                    .setMediationProvider(MAX_PROVIDER).build()
            ) {
                INIT_SUCCESS = true
                localBroadcastManager.sendBroadcast(Intent(INIT_SUCCESS_ACTION))
            }

//        AppLovinSdk.getInstance(this).settings.setVerboseLogging(true)
    }


}