package com.kdanmobile.reader.screen.reader.mediabox.stamp

import android.content.Context
import android.graphics.Rect
import android.support.constraint.ConstraintLayout
import android.support.v4.view.PagerAdapter
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import com.kdanmobile.kmpdfkit.annotation.stamp.StampConfig.STANDARD_STAMP_RES
import com.kdanmobile.kmpdfkit.annotation.stamp.TextStampConfig
import com.kdanmobile.kmpdfkit.annotation.stamp.view.KMPDFStampTextView
import com.kdanmobile.reader.R
import com.kdanmobile.reader.screen.data.StampAttribute
import com.kdanmobile.reader.screen.reader.mediabox.common.MediaBoxHeader
import kotlinx.android.synthetic.main.view_media_box_item_stamp_custom.view.*
import kotlinx.android.synthetic.main.view_media_box_item_stamp_standard.view.*
import kotlinx.android.synthetic.main.view_media_box_tab_stamp.view.*
import java.text.SimpleDateFormat
import java.util.*

class StampTabView : ConstraintLayout {

    private var selectedCustomStampIndex = 0
    private var selectedStandardStampIndex = 0

    var onMediaBoxHeaderClickListener: MediaBoxHeader.OnTitleButtonClickListener? = null
        set(value) {
            field = value
            titleButton_stamp?.onTitleButtonClickListener = field
        }

    constructor(context: Context) : super(context) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        initView()
    }

    private fun initView() {
        LayoutInflater.from(context).inflate(R.layout.view_media_box_tab_stamp, this)

        viewPager.adapter = StampViewPagerAdapter(arrayListOf(resources.getString(R.string.reader_mediaBox_stamp_tabCustom), resources.getString(R.string.reader_mediaBox_stamp_tabStandard)))
        tabLayout.setupWithViewPager(viewPager)
    }

    fun getStampAttribute() : StampAttribute {
        return when (viewPager.currentItem == 0) {
            true -> {
                val stampType = CustomStampType.values()[selectedCustomStampIndex]
                //  not work?
                val rect = Rect(0, 0, 100, 100)

                var timeType = KMPDFStampTextView.TimeType.NULL
                var timeText = ""
                when {
                    cb_date.isChecked && cb_time.isChecked -> {
                        timeType = KMPDFStampTextView.TimeType.TIME_AND_DATE
                        timeText = "${cb_date.text} ${cb_time.text}"
                    }
                    cb_date.isChecked && !cb_time.isChecked -> {
                        timeType = KMPDFStampTextView.TimeType.DATE
                        timeText = "${cb_date.text}"
                    }
                    !cb_date.isChecked && cb_time.isChecked -> {
                        timeType = KMPDFStampTextView.TimeType.TIME
                        timeText = "${cb_time.text}"
                    }
                }
                StampAttribute(
                        rect = rect,
                        config = TextStampConfig(
                                stampType.lineColor,
                                stampType.backgroundColor,
                                stampType.textColor,
                                et_mediaBoxItemStampCustom_text.text.toString(),
                                timeText,
                                stampType.shape,
                                timeType
                        )
                )
            }
            false -> {
                StampAttribute(STANDARD_STAMP_RES.values()[selectedStandardStampIndex])
            }
        }
    }

    fun hideSoftKeyboard() {
        val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(et_mediaBoxItemStampCustom_text.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    private inner class StampViewPagerAdapter(private val tabs: ArrayList<String>): PagerAdapter() {
        private val layoutInflater = LayoutInflater.from(context)

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val view = when (position) {
                0 -> {
                    val customStampView = layoutInflater.inflate(R.layout.view_media_box_item_stamp_custom, container, false)

                    val timer = Timer()
                    timer.schedule(object : TimerTask() {
                        override fun run() {
                            customStampView.post {
                                val date = Date()
                                cb_date.text = SimpleDateFormat("yyyy/MM/dd").format(date)
                                cb_time.text = SimpleDateFormat("HH:mm:ss").format(date).toLowerCase(Locale.US)
                            }
                        }
                    }, 0, 1000)

                    customStampView.addOnAttachStateChangeListener(object : OnAttachStateChangeListener{
                        override fun onViewAttachedToWindow(v: View?) {
                        }

                        override fun onViewDetachedFromWindow(v: View?) {
                            timer.cancel()
                        }
                    })

                    val recyclerView = customStampView.recyclerView_shapeCustom
                    recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
                    val adapter = CustomStampAdapter(context, CustomStampType.values())
                    adapter.setOnStampClickListener(object : OnStampClickListener {
                        override fun onStampClick(index: Int) {
                            selectedCustomStampIndex = index
                        }
                    })
                    recyclerView.adapter = adapter
                    recyclerView.setHasFixedSize(true)
                    customStampView
                }
                else -> {
                    val standardStampView = layoutInflater.inflate(R.layout.view_media_box_item_stamp_standard, container, false)
                    val recyclerView = standardStampView.recyclerView_shapeStandard
                    recyclerView.layoutManager = GridLayoutManager(context, resources.getInteger(R.integer.mediaBox_standardStamp_columnCount))
                    val adapter = StandardStampAdapter(context, STANDARD_STAMP_RES.values())
                    adapter.setOnStampClickListener(object : OnStampClickListener {
                        override fun onStampClick(index: Int) {
                            selectedStandardStampIndex = index
                        }
                    })
                    recyclerView.adapter = adapter
                    recyclerView.setHasFixedSize(true)
                    standardStampView
                }
            }
            container.addView(view)
            return view
        }

        override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
            container.removeView(obj as View)
        }

        override fun getCount(): Int {
            return tabs.size
        }

        override fun isViewFromObject(view: View, obj: Any): Boolean {
            return view == obj
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return tabs[position]
        }
    }
}