package com.mime.dualscreenview.data

import com.mime.dualscreenview.common.Blog
import com.mime.dualscreenview.data.model.BookPageInfo
import com.mime.dualscreenview.data.model.BookPageInfos
import com.mime.dualscreenview.data.model.HistoryItem
import com.mime.dualscreenview.data.model.LastInfo
import com.mime.dualscreenview.data.model.ReaderConfig
import io.realm.kotlin.Realm
import io.realm.kotlin.RealmConfiguration
import io.realm.kotlin.UpdatePolicy
import io.realm.kotlin.log.LogLevel
import io.realm.kotlin.types.BaseRealmObject
import io.realm.kotlin.types.TypedRealmObject
import kotlin.reflect.KClass

object HistoryManager {
    val clazz : Set<KClass<out BaseRealmObject>> = setOf(LastInfo::class, HistoryItem::class, ReaderConfig::class, BookPageInfos::class, BookPageInfo::class)
    val schemaVersion : Long = 5

    fun openRealm() : Realm  = Realm.open(RealmConfiguration.Builder(clazz as Set<KClass<out TypedRealmObject>>)
        .schemaVersion(schemaVersion)
        .log(LogLevel.ALL)
//        .deleteRealmIfMigrationNeeded()
        .build())

    fun save(lastInfo: LastInfo) {
        openRealm()?.apply{
            this.writeBlocking {
                copyToRealm(lastInfo, UpdatePolicy.ALL)
            }
        }?.close()
    }

    fun save(historyItem: HistoryItem) {
        openRealm()?.apply{
            this.writeBlocking {
                copyToRealm(historyItem, UpdatePolicy.ALL)
            }
        }?.close()
    }

    fun requestLastInfo(callback : (LastInfo)->Unit)  {
        openRealm()?.apply{

        }?.close()
    }

    fun save(config : ReaderConfig)  {
        openRealm()?.apply{
            this.writeBlocking {
                copyToRealm(config,UpdatePolicy.ALL)
            }
        }?.close()
    }

    fun getBooInfo(url : String ,callback : (BookPageInfos?)->Unit) {
        openRealm()?.apply{
            Blog.LOGE("get  ${url}" )
            Blog.LOGE("get  ${this.query(BookPageInfo::class).count().find()}" )
            var list = this.query(BookPageInfo::class).query("pathUrl == $0","${url}").find()
            if (list.size > 0) {
                var bookPageInfo = list.first()
                if (bookPageInfo != null) {
                    Blog.LOGE("get  ${bookPageInfo}")
                    this.query(BookPageInfos::class, "bookPageUrl == $0", bookPageInfo.bookPageUrl)
                        .find().first().let {
                        Blog.LOGE("get  ${it}  , ${it?.pages}")
                        callback.invoke(this.copyFromRealm(it))
                    }
                } else {
                    callback.invoke(null)
                }
            } else {
                var list = this.query(BookPageInfos::class).query("bookPageUrl == $0","${url}").find()
                if (list.size > 0) {
                    callback.invoke(this.copyFromRealm(list.first()))
                } else {
                    callback.invoke(null)
                }
            }
        }?.close()
    }

    fun getBooPageInfo(url : String ,callback : (BookPageInfo?)->Unit) {
        openRealm()?.apply{
            Blog.LOGE("get  ${url}" )
            Blog.LOGE("get  ${this.query(BookPageInfo::class).count().find()}" )
            var result = this.query(BookPageInfo::class).query("pathUrl == $0","${url}").find()
            if (result.size > 0) {
                var bookPageInfo = result?.first()
                if (bookPageInfo != null) {
                    callback.invoke(this.copyFromRealm(bookPageInfo))
                }
            }
        }?.close()
    }



    fun getNextPage(url : String ,callback : (BookPageInfo?)->Unit) {
        openRealm()?.apply{
            Blog.LOGE("getNextPage  ${url}" )
            Blog.LOGE("getNextPage  ${this.query(BookPageInfo::class).count().find()}" )
            var bookPageInfo = this.query(BookPageInfo::class).query("pathUrl == $0","${url}").find()?.first()
            Blog.LOGE("getNextPage 1 ${bookPageInfo}" )
            if (bookPageInfo != null) {
                Blog.LOGE("getNextPage 2  ${bookPageInfo.chapterNum}" )
                Blog.LOGE("getNextPage 2  ${bookPageInfo.bookPageUrl}" )
                var results = this.query(BookPageInfo::class).query("chapterNum == $0",bookPageInfo.chapterNum + 1).query("bookPageUrl == $0","${bookPageInfo.bookPageUrl}").find()
                if(results.size > 0) {
                    results.first()?.let {
                        Blog.LOGE("getNextPage 2  ${it.pathUrl}" )
                        callback.invoke(it)

                    }
                }
            }
        }?.close()
    }

    fun getPrevPage(url : String ,callback : (BookPageInfo?)->Unit) {
        openRealm()?.apply{
            Blog.LOGE("getPrevPage  ${url}" )
            Blog.LOGE("getPrevPage  ${this.query(BookPageInfo::class).count().find()}" )
            var bookPageInfo = this.query(BookPageInfo::class).query("pathUrl == $0","${url}").find()?.first()
            Blog.LOGE("getPrevPage  ${bookPageInfo}" )
            if (bookPageInfo != null) {
                Blog.LOGE("getPrevPage 2  ${bookPageInfo.chapterNum}" )
                Blog.LOGE("getPrevPage 2  ${bookPageInfo.bookPageUrl}" )
                var results = this.query(BookPageInfo::class).query("chapterNum == $0 && bookPageUrl == $1",bookPageInfo.chapterNum - 1,"${bookPageInfo.bookPageUrl}").find()
                if(results.size > 0) {
                    results.first()?.let {
                        callback.invoke(it)
                    }
                }
            }
        }?.close()
    }

}