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.Message
import android.text.InputType
import android.text.SpannableStringBuilder
import android.text.style.RelativeSizeSpan
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.View.*
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatButton
import androidx.constraintlayout.utils.widget.ImageFilterButton
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.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.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.Agit
import com.mime.dualscreenview.webcontents.contentsinfo.Booktoki
import com.mime.dualscreenview.webcontents.contentsinfo.GotoSomeWhere
import io.realm.kotlin.UpdatePolicy
import io.realm.kotlin.ext.copyFromRealm
import io.realm.kotlin.ext.query
import java.lang.System.currentTimeMillis
import java.text.SimpleDateFormat
import java.util.Date
import kotlin.random.Random


class Intro : Base() , MainControllInterface, PagedTextViewInterface {



    // Save previous state of dual screens


    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() {
        override fun handleMessage(msg: Message) {
//            super.handleMessage(msg)
            if (msg.what == 0 ) {
                (msg.obj as? ReaderConfig)?.let {

                }
            }
        }
    }

    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
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Blog.LOGD(log= "onCreate ${this::class.java.name} >> savedInstanceState ${savedInstanceState}")
        setContentView(R.layout.intro)
        findViewById<WebView>(R.id.menu_web)?.let {
            it.setOnLongClickListener {
                onTouch(TouchArea.Center)
                return@setOnLongClickListener false
            }
            mBaseWebContentsViewer = BaseWebContentsViewer(it,this)
        }

        paged_layer =findViewById<PagedTextLayout>(R.id.paged_layer)
        textview_title =findViewById<TextView>(R.id.textview_title)

        findViewById<ImageButton>(R.id.btn_list).setOnClickListener { v ->
            mBaseWebContentsViewer?.webview?.url?.let {
                Uri.parse(it).path?.let {
                    HistoryManager.getBooInfo(it, {
                        it?.let { showList(it) }
                    })
                }
            }
        }
        findViewById<WebView>(R.id.hidden_web)?.let { v->
            contentsSaver = v
            contentsSaver?.webViewClient = saveClient
            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()
//        }

        findViewById<View>(R.id.btn_setting).setOnClickListener { v->
            startActivity(Intent(this@Intro, Settings::class.java))
        }
        findViewById<View>(R.id.btn_history).setOnClickListener { v->
            var realm = openRealm()
            realm.query<HistoryItem>()?.find()?.let {
                showHistory(realm.copyFromRealm(it))
            }
            realm.close()
        }



        findViewById<View>(R.id.btn_home).setOnClickListener { v->
            paged_layer?.visibility = GONE
            mBaseWebContentsViewer.loadContents(Booktoki)
        }

        loadLastInfo()
    }

    fun loadLastInfo(){
        val realm = openRealm()
        try { lastInfo = realm?.query<LastInfo>()?.find()?.last()?.copyFromRealm() } catch (e : Exception) { }
        realm.close()
    }
    fun reloadLastInfo() {
        val configuration: Configuration = getResources().getConfiguration()
        if(lastInfo != null && lastInfo?.displayOrientation != configuration.orientation) {
//            findViewById<View>(R.id.btn_rotate).performClick()
        }
    }

    override fun onBookInfos(jsonString: String) {
        Blog.LOGE("onBookInfos" , "onBookInfos >> ${jsonString}")
        val realm = openRealm()
        var infos : BookPageInfos? = null
        realm.writeBlocking {
            try {

                var infosj : BookPageInfosJ? = null

                infosj =  Gson().fromJson(jsonString, BookPageInfosJ::class.java)
                Blog.LOGE("onBookInfos" , "onBookInfos 2 >> ${infosj}")
                Blog.LOGE("onBookInfos" , "onBookInfos 2 - 1 >> ${infosj?.pages}")
//                realm.createObjectFromJson
                Blog.LOGE("onBookInfos" , "onBookInfos 2 - 1 >> ${infosj?.getR()}")
                HistoryManager.getBooInfo(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())
                            }
                        }
                        Blog.LOGE("onBookInfos", "onBookInfos 3 >> ${realm.query<BookPageInfos>().find().size}")
                        Blog.LOGE("onBookInfos", "onBookInfos 4 >> ${realm.query<BookPageInfo>().find().size}")
                    } else {
                        infos = infosj?.getR()
                        if (infos != null) {
                            infos = copyToRealm(infos!!, UpdatePolicy.ALL)
                            for (item in infosj.pages) {
                                infos?.pages?.add(item.getRealm())
                            }
                            Blog.LOGE("onBookInfos", "onBookInfos 3 >> ${realm.query<BookPageInfos>().find().size}")
                            Blog.LOGE("onBookInfos", "onBookInfos 4 >> ${realm.query<BookPageInfo>().find().size}")
                        }
                    }
                }
                if (infos != null) {
                    infos = this.copyFromRealm(infos!!)
                }
            } catch (e :Exception) {
                e.printStackTrace()
            }
        }

        realm.close()
        infos?.bookPageUrl?.let {
            HistoryManager.getBooInfo(it){
                it?.let {
                    Blog.LOGE("onBookInfos" , "onBookInfos it >> ${it}")
                    runOnUiThread {
                        showList(it)
                    }
                }
            }
        }
    }

    fun reloadTo(lastInfo: LastInfo?) {
        findViewById<WebView>(R.id.menu_web)?.postDelayed({
            if (lastInfo != null) {
                mBaseWebContentsViewer.loadLastInfo(lastInfo!!)
            } else {
                mBaseWebContentsViewer.loadContents(Booktoki)
            }
        },200L)
    }
    override fun onResume() {
        super.onResume()
        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)
                }
            }
        }
        realm.close()
        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 ->
                        reloadTo(item.makeLastInfo())
                        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)
                            }
                        }
                        realm.close()
                        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) {

        if (infos != null && infos.pages.size ?: 0 > 0) {
            var items : ArrayList<BookPageInfo> = arrayListOf()
            for (item in infos.pages) {
                items.add(item)
            }
            items.sortBy { it.chapterNum }
            DefaultList.showDefaultList(
                this@Intro,
                "현제는 ${currentTitle} - ${(infos.pages.size ?: 0)  - currentChapter} -> 다른화를 골라",
                items,
                currentChapter,
                { position ->
                    return@showDefaultList items?.get(position)?.chapterTitle ?: ""
                },
                { position ->
                    items?.get(position)?.let { moveTo(it) }
                }, { state ->
                    if (state < 0 ) {
                        saveItem(infos)
                    }
                })
        }
    }
    var isLoading = false
    var saveClient = object : WebViewClient() {
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            isLoading = true
            Blog.LOGE("saveClient >>> ${isLoading} ${url}")
        }
        override fun onPageFinished(webView:  WebView?, url: String?) {
            super.onPageFinished(webView, url)
            isLoading = false
            var ramdomTimeSec = 1500L + Random(System.currentTimeMillis()).nextLong().rem(2999)
            Blog.LOGE("ramdomTime >>> ${ramdomTimeSec}")
            webView?.postDelayed( {
                Blog.LOGE("saveClient >>> ${isLoading} ${url}")
                var findContents = Booktoki.getFindContentsJs()
                Blog.LOGE("saveClient  find >>> ${findContents}")
                Random(System.currentTimeMillis()).nextLong().rem(999)
                webView?.evaluateJavascript(findContents){ result: String? ->
                    Blog.LOGE("saveClient  result >>> ${result}")
                    result?.let { string: String ->
                        Blog.LOGE("saveClient  contents >>> ${string.length}")
                        if (string.length > 10) {
                            Blog.LOGE("saveClient  it.length >>> ${string.length}")
                            var contents = string.replace("\\\"", "\"")
                            contents =
                                (contents.replace("\\n", System.getProperty("line.separator")))
                            Blog.LOGE("saveClient  contents >>> ${contents.length}")
                            Uri.parse(url)?.let {
                                it.path?.let {
                                    HistoryManager.getBooPageInfo(it) {
                                        HistoryManager.openRealm().apply {
                                            this.writeBlocking {
                                                it?.contents = contents
                                                if (it != null) {
                                                    copyToRealm(it, UpdatePolicy.ALL)
                                                }
                                            }
                                        }.close()
                                        runOnUiThread {
                                            it?.let {
                                                var origin = it.getTitleItem()
                                                val biggerText = SpannableStringBuilder(origin)
                                                biggerText.setSpan(RelativeSizeSpan(1.6f), 0, origin.length, 0)
                                                Toast.makeText(baseContext,biggerText, Toast.LENGTH_LONG).apply {
                                                    setGravity(Gravity.CENTER, 0, 0)
                                                }.show()
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        var ramdomTime = 10000L + Random(System.currentTimeMillis()).nextLong().rem(9999)
                        Blog.LOGE("ramdomTime >>> ${ramdomTime}")
                        contentsSaver?.postDelayed( { saveItem(null) }, ramdomTime)
                    }
                }},ramdomTimeSec)
        }
    }

    var saveTarget : ArrayList<BookPageInfo> = arrayListOf()
    private fun saveItem(infos: BookPageInfos?) {
        Blog.LOGE("saveItem >>> infos?.pages ${infos?.pages?.size ?: 0}")
        var savedCount = Random(System.currentTimeMillis()).nextLong().rem(19) +  6L
        infos?.pages?.reversed()?.forEach {
            if (it.contents?.length ?: 0 > 10) {
            } else {
                if (saveTarget.size < savedCount.toInt()) {
                    saveTarget.add(it)
                }
            }
        }

        Blog.LOGE("saveItem >>> saveTarget  ${saveTarget.count()}")
        if (isLoading == false) {
            try {
                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 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 {
            Uri.parse(mBaseWebContentsViewer.webview.url)?.let {
                it.path?.let {
                    HistoryManager.getNextPage(it) {
                        Blog.LOGE("HistoryManager.getNextPage(${it})")
                        if (it?.contents?.length ?: 0 > 10) {
                            currentBooinfo = it
                            paged_layer.text = it!!.contents!!
                            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!!))
                                paged_layer?.visibility = GONE
                            } else {
                                Blog.LOGE("HistoryManager.getNextPage(${Booktoki.getLastedDoamin()})")
                                mBaseWebContentsViewer.webview.loadUrl(Booktoki.getLastedDoamin() + it?.pathUrl!!)
                                paged_layer?.visibility = GONE
                            }
                            it?.pathUrl?.let {
                                HistoryManager.getBooInfo(it) {
                                    saveItem(it)
                                }
                            }
                        }
                    }
                }
            }
//            onNextClickAction?.let { it() }
        }
    }

    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 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 {
            Uri.parse(mBaseWebContentsViewer.webview.url)?.let {
                it.path?.let {
                    HistoryManager.getPrevPage(it) {
                        if (it?.contents?.length ?: 0 > 10) {
                            currentBooinfo = it
                            paged_layer.text = it!!.contents!!
                            paged_layer.visibility = VISIBLE
                        }

                        if(it?.pathUrl?.length ?: 0 > 0) {
                            HistoryManager.save(historyItem = HistoryItem().putHistory(it,mBaseWebContentsViewer.webview.url!!))
                            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(Booktoki.getLastedDoamin() + it?.pathUrl!!)
                            }
                        }
                    }
                }
            }
//            onPrevClickAction?.let{ it() }
        }
    }

    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
        }
    }


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

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onLoadedContents(aContents: String) {
        paged_layer.apply {
            if (aContents != null) {
                var contents = aContents.replace("\\\"","\"")
                contents = (contents.replace("\\n", System.getProperty("line.separator")))

                mPagedTextViewInterface = this@Intro
                var realm = HistoryManager.openRealm()
                realm.query<ReaderConfig>()?.find()?.let {
                    if (it.size > 0) {
                        realm.copyFromRealm(it.first())?.let {
                           runOnUiThread {
                               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)

                               var typeface = typesfacez.get(getIndex(typesfacez as PairArray<Any>,it.font ?: ""))
                               paged_layer?.setTypeface(resources.getFont(typeface.second))
                               val color = colorz.get(it.style ?: 0)
                               paged_layer?.setColorStyle(color.second)
                           }
                        }
                    }
                }
                realm.close()




//                text = (contents.replace("\\n", System.getProperty("line.separator")))
                if(lastInfo != null && mBaseWebContentsViewer.webview.url?.endsWith(lastInfo!!.pageUrl) ?: false) {
                    this@Intro.findViewById<ProgressBar>(R.id.progress)?.visibility = VISIBLE
                    paged_layer?.postDelayed({
                        this@Intro.findViewById<ProgressBar>(R.id.progress)?.visibility = GONE
                    },1000)
                }
                runOnUiThread {
                    text = (contents.replace("\\n", System.getProperty("line.separator")))
                    visibility = VISIBLE
                }
                forceUpdateUI()
                mBaseWebContentsViewer.webview.url?.let {
                    Uri.parse(it)?.let {
                        it.path?.let {
                            HistoryManager.getBooPageInfo(it){
                                currentBooinfo = it
                                HistoryManager.openRealm().apply {
                                    this.writeBlocking {
                                        it?.chapterTitle?.let {
                                            onFindTitle(it)
                                        }
                                        currentChapter = it?.chapterNum ?: 0
                                        currentPage = it?.chapterNum ?: 0
                                        it?.contents = contents
                                        if (it != null) {
                                            copyToRealm(it, UpdatePolicy.ALL)
                                        }
                                    }
                                }.close()
                                HistoryManager.save(historyItem = HistoryItem().putHistory(it,mBaseWebContentsViewer.webview.url!!))
                            }
                        }
                    }
                }
            }
        }
        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)
        }
        findViewById<ProgressBar>(R.id.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}")
        realm.close()
    }

    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.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}")
        realm.close()
    }
    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"
    }
}