package com.mime.dualscreenview.view

import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.util.AttributeSet
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.Guideline
import androidx.core.view.doOnLayout
import androidx.core.view.updateLayoutParams
import com.mime.dualscreenview.R
import com.mime.dualscreenview.common.Blog

class PagedTextLayout : ConstraintLayout , PagedTextGenerateInterface {
    constructor(context: Context) : super(context) {initView(context)}
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {initView(context)}
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {initView(context)}

    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {initView(context)}
    var mainTextView : TextView? = null
    var sencondTextView : TextView? = null
    var hiddenTextView : PagedTextView? = null
    var guideLine : Guideline? = null
    var pageList: ArrayList<CharSequence>? = null
    var text : String = ""
        set(new) {
            field = new
            hiddenTextView?.text = text
            hiddenTextView?.forceLayout()
        }

    private val hanler = Handler()
    var mPagedTextViewInterface : PagedTextViewInterface? = null
    val touchTimeover = Runnable {
        mPagedTextViewInterface?.onTimeoverTouch()
    }

    fun initView(context: Context) {
        inflate(context, R.layout.layout_textviewer, this)
        mainTextView = findViewById(R.id.first_view)
        sencondTextView = findViewById(R.id.sencond_view)
        hiddenTextView = findViewById(R.id.hidden_view)
        guideLine = findViewById(R.id.center_guide)
        hiddenTextView?.mPagedTextGenerateInterface = this
        hanler.removeCallbacks(touchTimeover)
        setOnTouchListener(object : OnSwipeTouchListener(context) {
            override fun onSwipeLeft() {
                mPagedTextViewInterface?.onSwipeLeft()
            }

            override fun onSwipeRight() {
                mPagedTextViewInterface?.onSwipeRight()
            }

            override fun onSingleTap(touchArea: TouchArea) {
                var isCenterTouch = TouchArea.Center.equals(touchArea)
                hanler.removeCallbacks(touchTimeover)
                mPagedTextViewInterface?.onTouch(touchArea)
                hanler?.postDelayed(touchTimeover, 3000L)
            }
        })
    }

    fun layoutChange(needDualPage: Boolean) {
        Blog.LOGD(log = "layoutChange>> ${this::class.java.name}")
        if (needDualPage) {
            findViewById<Guideline>(R.id.center_guide).updateLayoutParams<ConstraintLayout.LayoutParams> {
                guidePercent = 0.5f
            }
        } else {
            findViewById<Guideline>(R.id.center_guide).updateLayoutParams<ConstraintLayout.LayoutParams> {
                guidePercent = 1f
            }
        }
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        Blog.LOGD(log = "onLayout>> ${this::class.java.name}  changed >> ${changed}")
        if(!changed) {
            hiddenTextView?.text = text
            forceUpdateUI()
        }
    }
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        Blog.LOGD(log = "onSizeChanged>> ${this::class.java.name}")
        if (w != oldw || oldh != h) {
            postDelayed(Runnable {
                layoutChange(w > (h * 0.7f))

            },20)
        }else {

        }
    }


    var currentPage = 0
    override fun completePagination(pageList: ArrayList<CharSequence>) {
        Blog.LOGD(log = "completePagination>> ${this::class.java.name} >> pageList ${pageList}")
        if(text.length > 0 && pageList!= null && pageList.size == 0) {

        } else {
            this.pageList = pageList
            setPageBy(0)
        }
    }

    fun setColorStyle(colors : Array<String>) {
        setBackgroundColor(Color.parseColor(colors.get(1)))
        mainTextView?.setBackgroundColor(Color.parseColor(colors.get(1)))
        sencondTextView?.setBackgroundColor(Color.parseColor(colors.get(1)))
        mainTextView?.setTextColor(Color.parseColor(colors.get(0)))
        sencondTextView?.setTextColor(Color.parseColor(colors.get(0)))
    }

//    fun setPagedTextViewInterface(pagedTextViewInterface: PagedTextViewInterface) = hiddenTextView?.setPagedTextViewInterface(pagedTextViewInterface)
    fun setText(replace: String) = hiddenTextView?.setText(replace)
    fun setTextSize(fl: Float) {
        hiddenTextView?.setTextSize(fl)
        mainTextView?.setTextSize(fl)
        sencondTextView?.setTextSize(fl)
    }

    fun next(page : Int) {

    }

    fun isDualPage() : Boolean {
        return (guideLine?.layoutParams as ConstraintLayout.LayoutParams).guidePercent != 1f
    }

    fun setPageBy(num : Int) {
        currentPage = num
        var realPage = if(isDualPage()) currentPage * 2 else currentPage
        mainTextView?.text = pageList?.get(realPage) ?: "NONE"
        if(isDualPage()) {
            realPage = realPage.inc()
            sencondTextView?.text = if(pageList?.size ?: 0 > realPage) { pageList?.get(realPage)} else { "끝"}
        } else {
            sencondTextView?.text = ""
        }
    }

    fun size(): Int = if(isDualPage()) Math.round((hiddenTextView?.size() ?:0)  * 0.5f) else hiddenTextView?.size() ?: 0
    fun current(): Int = currentPage
    fun doNext() {
        setPageBy(currentPage.inc())
    }

    fun doPrev() {
        setPageBy(currentPage.dec())
    }

    fun forceUpdateUI() {
        mPagedTextViewInterface?.onTouch(TouchArea.Center)
        hiddenTextView?.doUpdate()
        hanler?.postDelayed(touchTimeover, 3000L)
    }


}

