package com.mime.dualscreenview.view

import android.annotation.TargetApi
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.os.Handler
import android.util.AttributeSet
import android.view.View
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 demp : View? = null
    var hiddenTextView : PagedTextView? = null
    var guideLine : Guideline? = null
    var pageList: ArrayList<CharSequence>? = null
    var text : String = ""
        set(new) {
            Blog.LOGE("field >> ${field}")
            Blog.LOGE("new >> ${new}")
            field = new
            Blog.LOGE("field >> ${field}")
            hiddenTextView?.setTxtF(field)
            hiddenTextView?.visibility = VISIBLE
        }

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

    var currentPageTextView : TextView? = null
    fun initView(context: Context) {
        inflate(context, R.layout.layout_textviewer, this)
        mainTextView = findViewById(R.id.first_view)
        sencondTextView = findViewById(R.id.sencond_view)
        demp = findViewById(R.id.demp)
        currentPageTextView = findViewById(R.id.current_page)

        hiddenTextView = findViewById(R.id.hidden_view)
        hiddenTextView?.mPagedTextGenerateInterface = this
        currentPageTextView?.text = ""
        hanler.removeCallbacks(touchTimeover)
        setOnLongClickListener { v ->
            mPagedTextViewInterface?.onLongClick()
            return@setOnLongClickListener false
        }

        setOnTouchListener(SimpleFingerGestures(omfgl = object : SimpleFingerGestures.OnFingerGestureListener{
            override fun onSwipeUp(
                fingers: Int,
                gestureDuration: Long,
                gestureDistance: Double
            ): Boolean {
                mPagedTextViewInterface?.onSwipeUp(fingers)
                return false
            }

            override fun onSwipeDown(
                fingers: Int,
                gestureDuration: Long,
                gestureDistance: Double
            ): Boolean {
                mPagedTextViewInterface?.onSwipeDown(fingers)
                return false
            }

            override fun onSwipeLeft(
                fingers: Int,
                gestureDuration: Long,
                gestureDistance: Double
            ): Boolean {
                mPagedTextViewInterface?.onSwipeLeft(fingers)
                return false
            }

            override fun onSwipeRight(
                fingers: Int,
                gestureDuration: Long,
                gestureDistance: Double
            ): Boolean {
                mPagedTextViewInterface?.onSwipeRight(fingers)
                return false
            }

            override fun onPinch(
                fingers: Int,
                gestureDuration: Long,
                gestureDistance: Double
            ): Boolean {
                return false
            }

            override fun onUnpinch(
                fingers: Int,
                gestureDuration: Long,
                gestureDistance: Double
            ): Boolean {
                mPagedTextViewInterface?.onLongClick()
                return false
            }

            override fun onDoubleTap(fingers: Int): Boolean {
                hanler.removeCallbacks(touchTimeover)
                mPagedTextViewInterface?.onTouch(TouchArea.Center)
                hanler?.postDelayed(touchTimeover, 3000L)
                return false
            }
        }))
//        {
//            override fun onSwipeUp() {
//                mPagedTextViewInterface?.onLongClick()
//            }
//
//            override fun onSwipeDown() {
//                mPagedTextViewInterface?.onLongClick()
//            }
//            override fun onSwipeLeft() {
//                mPagedTextViewInterface?.onSwipeLeft()
//            }
//
//            override fun onSwipeRight() {
//                mPagedTextViewInterface?.onSwipeRight()
//            }
//
//            override fun onSingleTap(touchArea: TouchArea) {
//                if(TouchArea.Center.equals(touchArea)) {
//                    hanler.removeCallbacks(touchTimeover)
//                    mPagedTextViewInterface?.onTouch(touchArea)
//                    hanler?.postDelayed(touchTimeover, 3000L)
//                } else {
//                    mPagedTextViewInterface?.onTouch(touchArea)
//                }
//            }
//
//            override fun onDoubleTap(area: TouchArea) {
//                if(TouchArea.Center.equals(area)) {
////                    hanler.removeCallbacks(touchTimeover)
////                    mPagedTextViewInterface?.onTouch(area)
////                    hanler?.postDelayed(touchTimeover, 3000L)
//                } else {
//                    mPagedTextViewInterface?.onTouch(area)
//                }
//            }
//        })
    }

    fun layoutChange(needDualPage: Boolean) {
        Blog.LOGD(log = "layoutChange>> ${this::class.java.name}")
        if (needDualPage) {
            sencondTextView?.visibility = VISIBLE
            demp?.visibility = VISIBLE
        } else {
            sencondTextView?.visibility = GONE
            demp?.visibility = GONE
        }
    }

    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)
        }
        hiddenTextView?.visibility = GONE
    }

    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 sencondTextView?.visibility == VISIBLE
    }

    fun setPageBy(num : Int) {
        currentPage = num
        var realPage = if(isDualPage()) currentPage * 2 else currentPage
        Blog.LOGE("realPage = if(${pageList?.size} ?: 0 > ${realPage}) { realPage} else { ${(pageList?.size ?: 0) - 1 }}")
        realPage = if(pageList?.size ?: 0 > realPage) { realPage} else { (pageList?.size ?: 0) - 1 }
        currentPageTextView?.text = "${realPage + 1 }/${ pageList?.size ?: 0 + 1}"

        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 getFastPageCount() = if(isDualPage()) 3 else 6
    fun current(): Int = currentPage
    fun doNext(fast : Boolean = false) {
        if (fast) {
            setPageBy(if((currentPage + getFastPageCount()) >= 0) {
                currentPage + getFastPageCount()
            } else {size()})
        } else {
            setPageBy(currentPage.inc())
        }
    }

    fun doPrev(fast : Boolean = false) {
        if (fast) {
            setPageBy(if((currentPage - getFastPageCount()) >= 0) {
                currentPage - getFastPageCount()
            } else {0})
        } else {
            setPageBy(if(currentPage > 0 )currentPage.dec() else 0)
        }
    }

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

    override fun setPadding(left: Int, top: Int, right: Int, bottom: Int) {
        hiddenTextView?.setPadding(left,top,right, bottom)
        mainTextView?.setPadding(left,top,right, bottom)
        sencondTextView?.setPadding(left,top,right, bottom)
    }


    fun setTypeface(tf: Typeface?) {
        hiddenTextView?.setTypeface(tf)
        mainTextView?.setTypeface(tf)
        sencondTextView?.setTypeface(tf)
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    fun setLetterSpacing(letterSpacing: Float) {
        hiddenTextView?.letterSpacing = letterSpacing.times(0.01f)
        mainTextView?.letterSpacing = letterSpacing.times(0.01f)
        sencondTextView?.letterSpacing = letterSpacing.times(0.01f)
    }


    fun setLineSpacing(mult: Float) {
        hiddenTextView?.setLineSpacing(1f, 1f.plus(mult.times(0.01f)))
        mainTextView?.setLineSpacing(1f, 1f.plus(mult.times(0.01f)))
        sencondTextView?.setLineSpacing(1f, 1f.plus(mult.times(0.01f)))
    }
}

