package bums.lunatic.launcher.workers

import bums.lunatic.launcher.apps.SimpleContact
import bums.lunatic.launcher.model.AppInfo
import bums.lunatic.launcher.model.Astro
import bums.lunatic.launcher.model.BotCommandEentitie
import bums.lunatic.launcher.model.Condition
import bums.lunatic.launcher.model.Current
import bums.lunatic.launcher.model.CurrentPlayItem
import bums.lunatic.launcher.model.Day
import bums.lunatic.launcher.model.Forecast
import bums.lunatic.launcher.model.Forecastday
import bums.lunatic.launcher.model.Hour
import bums.lunatic.launcher.model.Location
import bums.lunatic.launcher.model.LocationLog
import bums.lunatic.launcher.model.NotificationItem
import bums.lunatic.launcher.model.RssData
import bums.lunatic.launcher.model.RssDataInterface
import bums.lunatic.launcher.model.TelegramBotUpdate
import bums.lunatic.launcher.model.TelegramChat
import bums.lunatic.launcher.model.TelegramData
import bums.lunatic.launcher.model.TelegramFrom
import bums.lunatic.launcher.model.TelegramMessage
import bums.lunatic.launcher.model.WeatherForcast
import bums.lunatic.launcher.utils.BLog
import io.realm.kotlin.Realm
import io.realm.kotlin.RealmConfiguration
import io.realm.kotlin.UpdatePolicy
import io.realm.kotlin.ext.query
import io.realm.kotlin.migration.AutomaticSchemaMigration
import io.realm.kotlin.types.BaseRealmObject
import io.realm.kotlin.types.TypedRealmObject
import kotlin.reflect.KClass

class CustMigration : AutomaticSchemaMigration {
     override fun migrate(migrationContext: AutomaticSchemaMigration.MigrationContext) {
         BLog.LOGE(migrationContext.oldRealm.configuration.schemaVersion.toString())

         BLog.LOGE(migrationContext.newRealm.configuration.schemaVersion.toString())

     }
 }
object WorkersDb {



    val clazz : Set<KClass<out BaseRealmObject>> = setOf(RssData::class, NotificationItem::class, AppInfo::class,SimpleContact::class, RecentCall::class, RecentSms::class, CurrentPlayItem::class,
        TelegramBotUpdate::class,    TelegramData::class,  TelegramMessage::class,  TelegramChat::class,   BotCommandEentitie::class,   TelegramFrom::class,
        WeatherForcast::class, Location::class, Current::class, Forecast::class, Condition::class, Forecastday::class, Day::class, Astro::class, Hour::class,
        LocationLog::class
    )

    val schemaVersion : Long = 0L

    private var pRealm : Realm? = null
    fun getRealm() : Realm {
        if (pRealm == null || pRealm?.isClosed() == true) {
            pRealm =  Realm.open(RealmConfiguration.Builder(clazz as Set<KClass<out TypedRealmObject>>)
                .migration(CustMigration(),true)
                .schemaVersion(schemaVersion)
                .deleteRealmIfMigrationNeeded()
                .build())
        }
        return pRealm!!
    }

    fun insertData(rssData: RssData) {
        getRealm().apply {
            this.writeBlocking {
                try {
                    this.copyToRealm(rssData, UpdatePolicy.ERROR)
                } catch (e : Exception) {

                }
            }
        }
    }

    fun insertBulkData(rssDatas: Collection<RssData>) {
        rssDatas.forEach {
            try {
                getRealm().writeBlocking {
                    try {
                        this.copyToRealm(it, UpdatePolicy.ERROR)
                    } catch (e : Exception) {

                    }
                }
            } catch (e : Exception) {
            }
        }
    }

    fun insertBulkInteface(rssInterfaceDatas: Collection<RssDataInterface>) {

        rssInterfaceDatas.forEach {
            try {
                getRealm().writeBlocking {
                    if (it is RssData) {
                        try {
                            this.copyToRealm(it, UpdatePolicy.ERROR)
                        } catch (e : Exception) {

                        }
                    }
                }
            } catch (e : Exception) {
            }
        }
    }

    fun insertNoti(data: NotificationItem) {
        getRealm().apply {
            this.writeBlocking {
                try {
                    this.copyToRealm(data, UpdatePolicy.ALL)
                } catch (e : Exception) {

                }
            }
        }
    }

    fun update(info: AppInfo) {
        getRealm().apply {
            this.writeBlocking {
                try {
                    this.copyToRealm(info, UpdatePolicy.ALL)
                } catch (e : Exception) {

                }
            }
        }
    }

    fun update(contact: SimpleContact) {
        getRealm().apply {
            this.writeBlocking {
                try {
                    this.copyToRealm(contact, UpdatePolicy.ALL)
                } catch (e : Exception) {

                }
            }
        }
    }
    fun insertCall(contact: RecentCall) {
        getRealm().apply {
            this.writeBlocking {
                try {
                    this.copyToRealm(contact, UpdatePolicy.ALL)
                } catch (e : Exception) {

                }
            }
        }
    }

    fun updateAppUse(pkg : String) {
        getRealm().writeBlocking {
            val result = query<AppInfo>().query("pkgName == $0",pkg).find()
            if(result.size > 0) {
                val appInfo = result.first()
                appInfo.clickCount = appInfo.clickCount + 1
                appInfo.lastUseDate = System.currentTimeMillis()
            }
        }
    }

    fun push(loc: LocationLog) {
        getRealm().writeBlocking {
            try {
                this.copyToRealm(loc, UpdatePolicy.ALL)
            } catch (e : Exception) {

            }
        }
    }

}