package com.mime.dualscreenview.activity

import android.content.DialogInterface
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.InputType
import android.text.SpannableStringBuilder
import android.text.style.RelativeSizeSpan
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.View.inflate
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.utils.widget.ImageFilterButton
import androidx.core.net.toUri
import com.google.gson.Gson
import com.mime.dualscreenview.R
import com.mime.dualscreenview.common.Blog
import com.mime.dualscreenview.common.PairArray
import com.mime.dualscreenview.common.PrefManager
import com.mime.dualscreenview.common.colorz
import com.mime.dualscreenview.common.getIndex
import com.mime.dualscreenview.common.typesfacez
import com.mime.dualscreenview.data.HistoryManager
import com.mime.dualscreenview.data.model.BookPageInfo
import com.mime.dualscreenview.data.model.BookPageInfos
import com.mime.dualscreenview.data.model.BookPageInfosJ
import com.mime.dualscreenview.data.model.HistoryItem
import com.mime.dualscreenview.data.model.LastInfo
import com.mime.dualscreenview.data.model.ReaderConfig
import com.mime.dualscreenview.databinding.IntroBinding
import com.mime.dualscreenview.dialog.DefaultList
import com.mime.dualscreenview.view.PagedTextLayout
import com.mime.dualscreenview.view.PagedTextViewInterface
import com.mime.dualscreenview.view.TouchArea
import com.mime.dualscreenview.webcontents.BaseWebContentsViewer
import com.mime.dualscreenview.webcontents.MainControllInterface
import com.mime.dualscreenview.webcontents.contentsinfo.GotoSomeWhere
import com.mime.dualscreenview.webcontents.contentsinfo.NewtokiOne
import io.realm.kotlin.UpdatePolicy
import io.realm.kotlin.ext.copyFromRealm
import io.realm.kotlin.ext.query
import org.jsoup.Jsoup
import java.lang.System.currentTimeMillis
import java.text.SimpleDateFormat
import java.util.Date
import kotlin.random.Random


class Intro : Base() , MainControllInterface, PagedTextViewInterface {

    private lateinit var mBaseWebContentsViewer : BaseWebContentsViewer
    var lastInfo : LastInfo? = null
    lateinit var paged_layer : PagedTextLayout
    lateinit var textview_title : TextView
    var currentBooinfo : BookPageInfo? = null

    val handle = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            if (msg.what == 0 ) {
                (msg.obj as? ReaderConfig)?.let {
                }
            }
        }
    }



    fun getCurrentUrl() : String {
        var currentPath = currentBooinfo?.pathUrl ?: mBaseWebContentsViewer.webview.url?.toUri()?.path ?: ""
        var domain = PrefManager.getLastDomain()
        return domain.plus(if (currentPath.length > 4) currentPath else "")
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        Blog.LOGD(log= "onConfigurationChanged ${this::class.java.name} >> newConfig ${newConfig}")
        mBaseWebContentsViewer.webview.reload()
    }

    var contentsSaver : WebView? = null
    lateinit var binding : IntroBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Blog.LOGD(log= "onCreate ${this::class.java.name} >> savedInstanceState ${savedInstanceState}")
        binding = IntroBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.menuWeb.let {
            it.setOnLongClickListener {
                onTouch(TouchArea.Center)
                return@setOnLongClickListener false
            }
            mBaseWebContentsViewer = BaseWebContentsViewer(it,this)
        }

        paged_layer = binding.pagedLayer
        textview_title = binding.textviewTitle

        binding.btnList.setOnClickListener { v ->
            mBaseWebContentsViewer?.webview?.url?.let {
                Uri.parse(it).path?.let {
                    HistoryManager.getBookInfos(it, {
                        it?.let {
                            it.pages.sortBy { it.pathUrl }
                            showList(it)
                        }
                    })
                }
            }
        }
        binding.hiddenWeb?.let { v->
            contentsSaver = v
            contentsSaver?.webViewClient = saveClient
            try {
                contentsSaver?.removeJavascriptInterface("MyJavaScriptInterface")
            } catch (e:Exception) {e.printStackTrace()}
            contentsSaver?.addJavascriptInterface(SaveHelper(),"MyJavaScriptInterface")
            contentsSaver?.settings?.textZoom = 100
            contentsSaver?.settings?.javaScriptEnabled = true
            contentsSaver?.settings?.javaScriptCanOpenWindowsAutomatically = false
            contentsSaver?.settings?.loadWithOverviewMode = true
            contentsSaver?.settings?.setPluginState(WebSettings.PluginState.ON)
            contentsSaver?.settings?.domStorageEnabled = true
            contentsSaver?.clearCache(true);
            contentsSaver?.clearHistory();
            contentsSaver?.clearSslPreferences();
        }

//        findViewById<View>(R.id.btn_rotate).setOnClickListener { v->
//            switcvhOrient()
//        }

        binding.btnSetting.setOnClickListener { v->
            startActivity(Intent(this@Intro, Settings::class.java))
        }
        binding.btnHistory.setOnClickListener { v->
            var realm = openRealm()
            realm.query<HistoryItem>().find().let {
                showHistory(realm.copyFromRealm(it))
            }
        }


        binding.btnHome.setOnClickListener { v->
            paged_layer.visibility = GONE
            mBaseWebContentsViewer.loadContents(NewtokiOne)
        }

        loadLastInfo()
    }

    fun loadLastInfo(){
        val realm = openRealm()
        try { lastInfo = realm.query<LastInfo>().find().last()?.copyFromRealm()
            try {
                if (lastInfo != null) {
                    HistoryManager.getBookPageInfo(Uri.parse(lastInfo!!.pageUrl!!).path!!) {
                        it?.let {
                            currentBooinfo = it
                            paged_layer.visibility = VISIBLE
                            if(it?.pathUrl?.length ?: 0 > 0) {
                                HistoryManager.save(historyItem = HistoryItem().putHistory(it,mBaseWebContentsViewer.webview.url!!))
                                Blog.LOGE("HistoryManager.getNextPage(${it?.pathUrl})")
                                if (lastInfo?.pageUrl?.length ?: 0 > 0 && lastInfo?.pageUrl!!.startsWith("http")) {
                                    Blog.LOGE("HistoryManager.getNextPage(${lastInfo?.pageUrl})")
                                    mBaseWebContentsViewer.webview.loadUrl(lastInfo!!.pageUrl!!.replace(Uri.parse(lastInfo!!.pageUrl)!!.path!!,it?.pathUrl!!))
                                } else {
                                    Blog.LOGE("HistoryManager.getNextPage(${NewtokiOne.getLastedDoamin()})")
                                    mBaseWebContentsViewer.webview.loadUrl(NewtokiOne.getLastedDoamin() + it?.pathUrl!!)
                                }
                                it?.pathUrl?.let {
                                    HistoryManager.getBookInfos(it) {
                                        saveItem(it)
                                    }
                                }
                            }

                            HistoryManager.openRealm.query<ReaderConfig>()?.find()?.let {
                                if (it.size > 0) {
                                    realm.copyFromRealm(it.first()).let {
                                        applyReaderConfig()
                                    }
                                }
                            }
                            paged_layer.text = it!!.contents!!
                        }
                    }
                }
            }catch (e1 : Exception){

            }} catch (e : Exception) { }

    }

    fun reloadLastInfo() {
        val configuration: Configuration = getResources().getConfiguration()
        if(lastInfo != null && lastInfo?.displayOrientation != configuration.orientation) {
//            findViewById<View>(R.id.btn_rotate).performClick()
        }
    }

    override fun onBookInfos(aInfos: BookPageInfos) {
        Blog.LOGE("onBookInfos(aInfos: ${aInfos})")
        runOnUiThread {
            showList(aInfos)
        }
    }

    override fun onBookInfos(jsonString: String) {
        Blog.LOGE("onBookInfos" , "jsonString >> ${jsonString}")
        val realm = openRealm()
        var infos : BookPageInfos? = null
        realm.writeBlocking {
            try {
                var infosj : BookPageInfosJ? = null
                infosj =  Gson().fromJson(jsonString, BookPageInfosJ::class.java)
                HistoryManager.getBookInfos(infosj.bookPageUrl!!){
                    if (it != null) {

                        infos = copyToRealm(it!!, UpdatePolicy.ALL)
                        for (item in infosj.pages) {
                            if (infos!!.hasItem(item.getRealm()) == false) {
                                infos!!.pages.add(item.getRealm())
                            }
                        }
                        if (infos != null) {
                            infos = this.copyFromRealm(infos!!)
                        }
                    } else {
                        infos = infosj?.getR()
                        if (infos != null) {
                            infos = copyToRealm(infos!!, UpdatePolicy.ALL)
                            for (item in infosj.pages) {
                                infos?.pages?.add(item.getRealm())
                            }
                        }
                        if (infos != null) {
                            infos = this.copyFromRealm(infos!!)
                        }
                    }
                }

            } catch (e :Exception) {
                e.printStackTrace()
            } finally {
                infos?.bookPageUrl?.let {
                    HistoryManager.getBookInfos(it){
                        it?.let {
                            Blog.LOGE(s(), "onBookInfos it >> ${it}")
                            runOnUiThread {
                                showList(it)
                            }
                        }
                    }
                }
            }
        }
    }

    private fun s() = "onBookInfos"

    fun reloadTo(lastInfo: LastInfo?) {
        findViewById<WebView>(R.id.menu_web)?.postDelayed({
            if (lastInfo != null) {
                mBaseWebContentsViewer.loadLastInfo(lastInfo!!)
            } else {
                mBaseWebContentsViewer.loadContents(NewtokiOne)
            }
        },200L)
    }

    override fun onStart() {
        super.onStart()
        proceedLastPage()
    }

    override fun onResume() {
        super.onResume()
    }


    fun proceedLastPage() {
        var realm = HistoryManager.openRealm
        realm.query<ReaderConfig>()?.find()?.let {
            if (it.size > 0) {
                realm.copyFromRealm(it.first())?.let {
                    var msg = handle.obtainMessage()
                    msg.what = 0
                    msg.obj = it
                    handle.sendMessageDelayed(msg, 200)
                }
            }
        }
        reloadLastInfo()
        reloadTo(lastInfo)
    }

    fun switcvhOrient(){
//        val configuration: Configuration = getResources().getConfiguration()
//        setRequestedOrientation(
//            if(configuration.orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE }
//            else {ActivityInfo.SCREEN_ORIENTATION_PORTRAIT}
//        )
    }

    fun showHistory(infos: List<HistoryItem>) {

        val builderSingle: AlertDialog.Builder = AlertDialog.Builder(this@Intro)
        builderSingle.setTitle("${currentTitle} : ${currentChapter} -> Select One ")
        val arrayAdapter =
            ArrayAdapter<String>(this@Intro, android.R.layout.select_dialog_singlechoice)
        for (item in infos) {
            arrayAdapter.addAll(item.title)
        }

        builderSingle.setNegativeButton("cancel",
            DialogInterface.OnClickListener { dialog, which -> dialog.dismiss() })

        builderSingle.setAdapter(arrayAdapter,
            DialogInterface.OnClickListener { dialog, which ->
                val strName = arrayAdapter.getItem(which)
                val item = infos.get(which)
                val builderInner: AlertDialog.Builder = AlertDialog.Builder(this@Intro)
                builderInner.setMessage(strName)
                builderInner.setTitle("${infos.get(which).title}로 이동 고고!?")
                builderInner.setPositiveButton("Ok",
                    DialogInterface.OnClickListener {
                            dialog, which ->
                        contentsLoad(item.pageUrl)
                        dialog.dismiss()
                    })
                builderInner.setNeutralButton("삭제",
                    DialogInterface.OnClickListener {
                            dialog, which ->
                        var realm = openRealm()
                        realm?.writeBlocking {
                            this.query<HistoryItem>().query("title == '${item.title}'").find()?.last()?.let{
                                this.delete(it)
                            }
                        }
                        dialog.dismiss()
                    })
                builderInner.setNegativeButton("취소",
                    DialogInterface.OnClickListener {
                            dialog, which ->
                        dialog.dismiss()
                    })
                builderInner.show()
            })
        var ddddd= builderSingle.create()
        ddddd.setOnShowListener { d->
            (d as? AlertDialog)?.let{
                it.listView?.setSelection(currentChapter)
            }
        }

        ddddd.show()
    }

    fun showList(infos: BookPageInfos) {
        Blog.LOGE("showList infos >>>>${infos}")
        if (infos != null && infos.pages.size ?: 0 > 0) {
            var items : ArrayList<BookPageInfo> = arrayListOf()
            for (item in infos.pages) {
                items.add(item)
            }

            items.sortBy { it.chapterID }

            DefaultList.showDefaultList(
                this@Intro,
                "현제는 ${currentTitle} - ${currentChapter} -> 다른화를 골라",
                items,
                currentChapter,
                { position ->
                    return@showDefaultList items?.get(position)?.chapterTitle ?: ""
                },
                { position ->
                    items?.get(position)?.let { moveTo(it) }
                }, { state ->
                    if (state < 0 ) {
                        saveItem(infos)
                    }
                })
        }
    }
    val String.cleanTextContent: String
        get() {
            // strips off all non-ASCII characters
            var text = this
            text = text.replace("[^\\x00-\\x7F]".toRegex(), "")

            // erases all the ASCII control characters
            text = text.replace("[\\p{Cntrl}&&[^\r\n\t]]".toRegex(), "")

            // removes non-printable characters from Unicode
            text = text.replace("\\p{C}".toRegex(), "")
            return text.trim()
        }

    var isLoading = false
    var saveClient = object : WebViewClient() {

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            isLoading = true
        }

        override fun onPageFinished(webView:  WebView?, url: String?) {
            super.onPageFinished(webView, url)
//            val delayed = 3500L + Math.abs(Random.nextLong().rem(9999L))
            finishedUrl = url ?: ""
            webView?.postDelayed({
                webView?.evaluateJavascript(
                    "function getAll() {\n" +
                            "           MyJavaScriptInterface.sendValueFromHtml(document.getElementsByTagName('html')[0].innerHTML)" +
                            "        };getAll()"
                ) { result ->
                    (result as? String)?.let {

                    }
                    isLoading = false
                }
            }, delayed)
        }


    }
    fun showToast(origin: String) {
        runOnUiThread {
            val toast = Toast(this)
            toast.duration = Toast.LENGTH_SHORT
            val biggerText = SpannableStringBuilder(origin)
            biggerText.setSpan(RelativeSizeSpan(1.6f), 0, origin.length, 0)
            val view: View = inflate(this, com.mime.dualscreenview.R.layout.simple_toast,null)
            view.findViewById<TextView>(com.mime.dualscreenview.R.id.text).text = biggerText
            toast.setView(view)
            toast.show()
//            Toast.makeText(
//                baseContext,
//                biggerText,
//                Toast.LENGTH_SHORT
//            ).show()
        }
    }
    var delayed = 3500L + Math.abs(Random.nextLong().rem(9999L))
    var finishedUrl : String? = null
    inner class SaveHelper {
        @JavascriptInterface
        fun sendValueFromHtml(string: String) {
            Jsoup.parse(string)?.let { html ->
                val view_padding =  html.getElementsByClass("view-padding")
                if (view_padding.size > 0){
//                    Blog.LOGE("finishedUrl >>> ${finishedUrl}  :::: ${html.title()}")
                    val contents = view_padding.get(0).children().html().replace("<p>"," ").replace("</p>","\n\n")
//                    Blog.LOGE("finishedUrl >>> ${finishedUrl}  :::: view_padding.get(0)\n${contents}")
                    if (contents.length > 20) {
                        Uri.parse(finishedUrl).path?.let {
                            delayed = 3500L + Math.abs(Random.nextLong().rem(9999L))
                            HistoryManager.getBooPageInfoContentsSave(it, contents).apply {
                                HistoryManager.getBookPageInfo(it) { book ->
                                    showToast("saved ${book?.getTitleItem()} \n:: lenght  = ${contents.length} \n:: saveTarget = ${saveTarget.size}\n:: delayed >> ${delayed}")
                                }
                            }.apply {
                                HistoryManager.getBookInfos(it) { saveItem(it)}
                            }
                        }
                    }
                } else {
                }
            }
        }
    }
    var saveTarget : ArrayList<BookPageInfo> = arrayListOf()
    private fun saveItem(infos: BookPageInfos?) {
        Blog.LOGE("saveItem >>> infos?.pages ${infos?.pages?.size ?: 0}")
        var savedCount = Math.abs(Random(System.currentTimeMillis()).nextLong().rem(9) +  6L)
        Blog.LOGE("saveItem >>> targetCount =  ${savedCount}")

        infos?.pages?.reversed()?.forEach {
            if ((it.contents?.length ?: 0) > 10) {
            } else {
                if (savedCount.toInt() > 0) {
                    saveTarget.add(it)
                    savedCount = savedCount - 1L
                }
            }
        }

        if (savedCount > 0) {
            HistoryManager.openRealm.query<BookPageInfo>().find().forEach {
                if ((it.contents?.length ?: 0) > 10) {
                } else if(savedCount.toInt() > 0) {
                    saveTarget.add(HistoryManager.openRealm.copyFromRealm(it))
                    savedCount = savedCount - 1
                }
            }
        }

        Blog.LOGE("saveItem >>> saveTarget  ${saveTarget.count()}")
        try {
            if (isLoading == false) {
                saveTarget.removeFirst().let {
                    Blog.LOGE("saveItem >>> ${it.pathUrl}")
                    runOnUiThread {
                        mBaseWebContentsViewer.webview.url?.let { currentUrl ->
                            currentUrl.replace(Uri.parse(currentUrl).path ?: "", it.pathUrl ?: "")
                                ?.let { targetUrl ->
                                    Blog.LOGE("targetUrl >>> ${targetUrl}")
                                    contentsSaver?.loadUrl(targetUrl)
                                }
                        }
                    }
                }
            }
        } catch ( e : Exception) {
            e.printStackTrace()
        }
    }

    private fun moveTo(item: BookPageInfo?) {
        item?.pathUrl?.let { newPath ->
            if (item.contents?.length ?: 0 > 10) {
                paged_layer.text = item!!.contents!!
                paged_layer.visibility = VISIBLE
            }
            mBaseWebContentsViewer?.webview?.url?.let { currentUrl ->
                Uri.parse(currentUrl)?.path?.let {
                    currentUrl.replace(it, newPath)?.let {
                        mBaseWebContentsViewer?.webview?.loadUrl(it)
                    }
                }
            }
        }
    }

//    fun showStyleList() {
//        var mStylez = Stylez(this@Intro)
//        mStylez.styleSelectInterface = object : StyleSelectInterface {
//            override fun onSelectStyle(bgColor: String, textColor: String) {
//                paged_layer?.setColorStyle(arrayOf(textColor,bgColor))
//            }
//        }
//        mStylez.show()
//    }


    override fun onDestroy() {

        super.onDestroy()
    }


    var onNextClickAction: GotoSomeWhere? = null
    override fun showNextBtn(find : Boolean , onClickAction: GotoSomeWhere) {
        onNextClickAction = onClickAction
        findViewById<ImageFilterButton>(R.id.btn_right)?.let{
            it.setOnClickListener {
                actionNextEvent()
            }
            it.visibility= if(find) VISIBLE else GONE
        }
    }



    fun moveToNext(pathUrl : String?) {
        if (pathUrl != null && pathUrl.length > 6) {
            HistoryManager.getNextPage(pathUrl!!) {
                if(it != null && it!!.pathUrl?.length ?: 0 > 6) {contentsLoad(it.pathUrl!!)}
            }
        }
    }
    fun moveToPrev(pathUrl : String?) {
        if (pathUrl != null && pathUrl.length > 6) {
            HistoryManager.getPrevPage(pathUrl!!) {
                if(it != null && it!!.pathUrl?.length ?: 0 > 6) {contentsLoad(it.pathUrl!!)}
            }
        }
    }

    fun contentsLoad(pathUrl : String) {
        HistoryManager.getBookPageInfo(pathUrl) {
            Blog.LOGE("contentsLoad :::: pathUrl >> ${pathUrl}")
            it?.pathUrl?.let {
                Blog.LOGE("contentsLoad :::: pathUrl >> ${it}")
                HistoryManager.getBookInfos(it) {
                    Blog.LOGE("contentsLoad :::: getBookInfos >> ${it}")
                    saveItem(it)
                }
            }
            if (it != null)  currentBooinfo = it
            if (it != null && (it?.contents?.length ?: 0) > 10) {
                paged_layer.visibility = VISIBLE
                if((it?.pathUrl?.length ?: 0) > 0) {
                    if (lastInfo?.pageUrl?.length ?: 0 > 0 && lastInfo?.pageUrl!!.startsWith("http")) {
                        mBaseWebContentsViewer.webview.loadUrl(lastInfo!!.pageUrl!!.replace(Uri.parse(lastInfo!!.pageUrl)!!.path!!,it?.pathUrl!!))
                    } else {
                        mBaseWebContentsViewer.webview.loadUrl(NewtokiOne.getLastedDoamin() + it?.pathUrl!!)
                    }
                    HistoryManager.save(historyItem = HistoryItem().putHistory(it,mBaseWebContentsViewer.webview.url!!))
                }
                applyReaderConfig()
                paged_layer.text = it!!.contents!!
            } else {
                if(it?.pathUrl?.length ?: 0 > 0) {
                    if (lastInfo?.pageUrl?.length ?: 0 > 0 && lastInfo?.pageUrl!!.startsWith("http")) {
                        paged_layer.visibility = GONE
                        mBaseWebContentsViewer.webview.loadUrl(lastInfo!!.pageUrl!!.replace(Uri.parse(lastInfo!!.pageUrl)!!.path!!,it?.pathUrl!!))
                    } else {
                        paged_layer.visibility = GONE
                        mBaseWebContentsViewer.webview.loadUrl(NewtokiOne.getLastedDoamin() + it?.pathUrl!!)
                    }
                    HistoryManager.save(historyItem = HistoryItem().putHistory(it,mBaseWebContentsViewer.webview.url!!))
                }
            }
        }
    }




    fun actionNextEvent(fast : Boolean = false) {
        if (paged_layer != null && paged_layer!!.visibility == View.VISIBLE && paged_layer!!.size() > 0 && (paged_layer!!.current() < paged_layer!!.size() - 1) ) {
            paged_layer!!.doNext(fast)
            updateLastInfo(paged_layer!!)
        } else {
            moveToNext(currentBooinfo?.pathUrl ?: mBaseWebContentsViewer.webview.url?.toUri()?.path)
        }
    }

    var onPrevClickAction: GotoSomeWhere? = null
    override fun showPrevBtn(find : Boolean, onClickAction: GotoSomeWhere) {
        onPrevClickAction = onClickAction
        findViewById<ImageFilterButton>(R.id.btn_left)?.let{
            it.setOnClickListener {
                actionPrevEvent()
            }
            it.visibility= if(find) VISIBLE else GONE
        }
    }

    fun applyReaderConfig() {
        var realm = HistoryManager.openRealm
        realm.query<ReaderConfig>()?.find()?.let {
            if (it.size > 0) {
                realm.copyFromRealm(it.first())?.let {
                    runOnUiThread {
                        var typeface = typesfacez.get(getIndex(typesfacez as PairArray<Any>,it.font ?: ""))
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            paged_layer?.setTypeface(resources.getFont(typeface.second))
                        }

                        val color = colorz.get(it.style ?: 0)
                        paged_layer?.setColorStyle(color.second)
                        paged_layer.setTextSize(it.textSize?.toFloat()?: 14f)
                        paged_layer.setLineSpacing(it.lineSpace?.toFloat() ?: 1f)
                        paged_layer.setLetterSpacing(it.letterSpace?.toFloat() ?: 1f)
                        paged_layer.setPadding(
                            it.padding ?: 1,
                            it.padding ?: 1,
                            it.padding ?: 1,
                            it.padding ?: 1)
                        paged_layer.invalidate()
                    }
                }
            }
        }
    }

    fun actionPrevEvent(fast : Boolean = false) {
        if (paged_layer != null && paged_layer!!.visibility == View.VISIBLE && paged_layer!!.size() > 0 && paged_layer!!.current() > 0 ) {
            paged_layer!!.doPrev(fast)
            updateLastInfo(paged_layer!!)
        } else {
            moveToPrev(currentBooinfo?.pathUrl ?: mBaseWebContentsViewer.webview.url?.toUri()?.path)
        }
    }

    override fun onBackPressed() {

//        super.onBackPressed()
        var layer = findViewById<PagedTextLayout>(R.id.paged_layer)

//        if (!didBackPress) {
//            firstBackPress()
//            return
//        }

        if (layer != null && layer.visibility == View.VISIBLE) {
            didBackPress = false
            layer.visibility = GONE
            onTouch(TouchArea.Center)
            return
        }

        if (mBaseWebContentsViewer.webview.canGoBack()) {
            mBaseWebContentsViewer.webview.goBack()
            return
        }

        if (!didBackPress) {
            firstBackPress()
            return
        } else {
            finishAffinity()
            didBackPress = false
//            super.onBackPressed()
        }
    }


    override fun showAlert(alert: String) {
        Log.i(TAG,"showAlert >> " + alert)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onLoadedContents(aContents: String) {
        paged_layer.apply {
            paged_layer.post {
                if (aContents != null && aContents.length > 10) {
                    var contents = aContents.replace("\\\"", "\"")
                    contents = (contents.replace("\\n", System.getProperty("line.separator")))
                    contents = (contents.replace("\\n", System.getProperty("line.separator")))
                    mPagedTextViewInterface = this@Intro
                    if (lastInfo != null && mBaseWebContentsViewer.webview.url?.endsWith(lastInfo!!.pageUrl) ?: false) {
                        binding.progress.visibility = VISIBLE
                        paged_layer.postDelayed({
                            binding.progress.visibility = GONE
                        }, 1000)
                    }
                    applyReaderConfig()
                    runOnUiThread {
                        text = contents
                        visibility = VISIBLE
                    }
                    forceUpdateUI()
                    mBaseWebContentsViewer.webview.url?.let {
                        Uri.parse(it)?.let {
                            it.path?.let {
                                HistoryManager.getBookPageInfo(it) {
                                    currentBooinfo = it
                                    currentChapter = it?.chapterNum ?: 0
                                    currentPage = it?.chapterNum ?: 0
                                    HistoryManager.save(
                                        historyItem = HistoryItem().putHistory(
                                            it,
                                            mBaseWebContentsViewer.webview.url!!
                                        )
                                    )
                                }
                            }
                            HistoryManager.getBooPageInfoContentsSave(it!!.path!!, contents)
                        }
                    }
                }
            }
        }
        Log.i(TAG,"onLoadedContents >> " + aContents)
    }

    var currentTitle : String = ""
    var currentChapter : Int = 0

    override fun onFindTitle(contents: String) {
        textview_title.text = contents
        textview_title.setOnClickListener {
            val builder = AlertDialog.Builder(this)
            builder.setTitle("Title")
            val input = EditText(this)
            input.setText(mBaseWebContentsViewer?.webview?.url ?: "")
            input.inputType = InputType.TYPE_CLASS_TEXT
            builder.setView(input)
            builder.setPositiveButton(
                "OK"
            ) { dialog, which ->
                var m_Text = input.text.toString()
                mBaseWebContentsViewer?.webview?.loadUrl(m_Text.trim())
            }
            builder.setNegativeButton(
                "Cancel"
            ) { dialog, which -> dialog.cancel() }
            builder.show()
        }
        var testRegex = """[^0-9]""".toRegex();
        Blog.LOGI(TAG,"onFindTitle >> " + contents + "   :::  ${testRegex.replace(contents,"")}")
        if(contents.contains("-")) {
            currentTitle = contents.split("-")[0]
            try {
                currentChapter = testRegex.replace(contents.split("-")[1],"").toInt()
            } catch (e : Exception) {
                currentChapter = 0
            }
        } else if(testRegex.replace(contents,"").length > 0){
            currentChapter = testRegex.replace(contents,"").toInt()
            currentTitle = contents.split(testRegex.replace(contents,""))[0]
        } else {
            val dateFormat = "yyyyMMdd-HH"
            val date = Date(currentTimeMillis())
            val simpleDateFormat = SimpleDateFormat(dateFormat)
            currentTitle = simpleDateFormat.format(date)
        }

    }

    override fun onStartLoad() {
        findViewById<ProgressBar>(R.id.progress).visibility = VISIBLE
    }

    override fun completePageLoad(lastInfo: LastInfo) {
        val configuration: Configuration = getResources().getConfiguration()

        if(this.lastInfo == null || !(this.lastInfo?.pageUrl.equals(lastInfo?.pageUrl)) || this.lastInfo?.displayOrientation != configuration?.orientation) {
            lastInfo.displayOrientation = configuration?.orientation ?: ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            saveLastInfo(lastInfo)
        }
        binding.progress.visibility = GONE
    }

    fun saveLastInfo(lastInfo: LastInfo) {
        val realm = openRealm()
        if((realm.query<LastInfo>()?.count()?.find() ?: 0) > 0) {
            realm.writeBlocking {
                this.query<LastInfo>()?.find()?.last()?.let{
                    it.pageUrl = lastInfo.pageUrl
                    it.title = currentTitle
                    it.chapter = currentChapter
                    it.pageIndex = lastInfo.pageIndex
                    it.contentsName = lastInfo.contentsName
                    it.displayOrientation = lastInfo.displayOrientation
                    this@Intro.lastInfo = copyFromRealm(it)
                }
            }
        } else {
            realm.writeBlocking {
                copyToRealm(lastInfo)
            }
        }
        Blog.LOGD(log ="Successfully opened realm: ${realm.configuration.name}")

    }

    fun updateLastInfo(pagedTextLayout: PagedTextLayout) {
        val configuration: Configuration = getResources().getConfiguration()
        val realm = openRealm()
        realm.writeBlocking {
            this.query<LastInfo>()?.find()?.last()?.let{
                it.displayOrientation = configuration.orientation
                it.title = currentTitle
//                it.pageUrl = currentBooinfo?.pathUrl ?: mBaseWebContentsViewer.webview.url?.toUri()?.path ?: ""
                it.chapter = currentChapter
                it.pageIndex = pagedTextLayout.current()
                this@Intro.lastInfo = copyFromRealm(it)
            }
            if (currentTitle.length > 0 && currentChapter > 0) {
                this@Intro.lastInfo?.makeHistoryItem()?.let{
                    copyToRealm(it, UpdatePolicy.ALL)
                }
            }
        }

        Blog.LOGD(log ="Successfully opened realm: ${realm.configuration.name}")

    }
    override fun onKeyClick(keyCode: Int): Boolean {
        when(keyCode) {
            KeyEvent.KEYCODE_VOLUME_DOWN ->{actionNextEvent()}
            KeyEvent.KEYCODE_VOLUME_UP ->{actionPrevEvent()}
            KeyEvent.KEYCODE_VOLUME_MUTE -> {actionNextEvent()}

        }
        return super.onKeyClick(keyCode)
    }

    override fun onTouch(touchArea: TouchArea) {
        Blog.LOGD(log="onTouch ${touchArea}")
        when (touchArea) {
            TouchArea.Center-> {
                findViewById<View>(R.id.btn_right).visibility = VISIBLE
                findViewById<View>(R.id.btn_left).visibility = VISIBLE
                findViewById<View>(R.id.btn_setting).visibility = VISIBLE

                textview_title.visibility = VISIBLE
                findViewById<View>(R.id.btn_home).visibility = VISIBLE
                findViewById<View>(R.id.btn_list).visibility = VISIBLE
                findViewById<View>(R.id.btn_history).visibility = VISIBLE
//                findViewById<View>(R.id.btn_rotate).visibility = VISIBLE

            }
            TouchArea.Right -> {
                actionNextEvent()
            }
            TouchArea.Left-> {
                actionPrevEvent()
            }
            TouchArea.DoubleRight -> {
                actionNextEvent(true)
            }
            TouchArea.DoubleLeft -> {
                actionPrevEvent(true)
            }
            else -> {

            }
        }


    }

    override fun onLongClick() {
        Blog.LOGD(log="onLongClick")

    }
    override fun onSwipeLeft(count : Int) {
        Blog.LOGD(log="onSwipeLeft ${count}")
        actionNextEvent(count > 1)

    }

    override fun onSwipeRight(count : Int) {
        Blog.LOGD(log="onSwipeRight ${count}")
        actionPrevEvent(count > 1)
    }

    override fun onSwipeUp(touchCount: Int) {

    }

    override fun onSwipeDown(touchCount: Int) {
        if (touchCount == 2) {
            if (paged_layer?.visibility == VISIBLE) {
                paged_layer?.visibility = GONE
                findViewById<View>(R.id.btn_right).visibility = VISIBLE
                findViewById<View>(R.id.btn_left).visibility = VISIBLE
                findViewById<View>(R.id.btn_setting).visibility = VISIBLE

                textview_title.visibility = VISIBLE
                findViewById<View>(R.id.btn_home).visibility = VISIBLE
                findViewById<View>(R.id.btn_list).visibility = VISIBLE
                findViewById<View>(R.id.btn_history).visibility = VISIBLE
//                findViewById<View>(R.id.btn_rotate).visibility = VISIBLE
            }
        }
    }


    override fun onTimeoverTouch() {
        Blog.LOGD(log="onTimeoverTouch")
        findViewById<View>(R.id.btn_right).visibility = GONE
        findViewById<View>(R.id.btn_left).visibility = GONE
        findViewById<View>(R.id.btn_setting).visibility = GONE

        textview_title.visibility = GONE
        findViewById<View>(R.id.btn_home).visibility = GONE
        findViewById<View>(R.id.btn_list).visibility = GONE
        findViewById<View>(R.id.btn_history).visibility = GONE
//        findViewById<View>(R.id.btn_rotate).visibility = GONE

    }

    companion object {
        private const val TAG = "DualScreenStatus"
    }
}