package com.kdanmobile.reader.thumb

import android.graphics.Bitmap
import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.support.v7.widget.helper.ItemTouchHelper.Callback.makeMovementFlags
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.kdanmobile.reader.R
import com.kdanmobile.reader.screen.handler.ThumbnailHandler
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.item_pdf_thumb.view.*

class PdfThumbAdapter(var data: ThumbData, var handler: PageMoveHandler, private val thumbnailHandler: ThumbnailHandler): RecyclerView.Adapter<PdfThumbAdapter.ViewHolder>(), ItemMoveSwipeListener {

    override fun getItemCount(): Int {
        return data.pageCount
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(data, position, thumbnailHandler)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v1 = LayoutInflater.from(parent.context).inflate(R.layout.item_pdf_thumb, parent, false)
        val holder = ViewHolder(v1)
        holder.setSize(data.viewWidth, data.viewHeight, data.viewPadding, ScreenUtil.getDensity(parent.context))
        return ViewHolder(v1)
    }

    override fun onViewRecycled(holder: ViewHolder) {
        super.onViewRecycled(holder)
        holder.stopLoadThumbSync()
    }

    class ViewHolder (view : View) : RecyclerView.ViewHolder(view) {
        private var disposable: Disposable? = null

        fun bind(thumbData: ThumbData, position: Int, thumbnailHandler: ThumbnailHandler) {
            loadThumbSync(thumbData, position, thumbnailHandler)

            itemView.tv_pdfThumbGvItem_page.text = (position + 1).toString()
            itemView.cb_pdfThumbGvItem_.isChecked = thumbData.pageSelect[position] as Boolean
            itemView.tv_pdfThumbGvItem_page.setTextColor(if (itemView.cb_pdfThumbGvItem_.isChecked) ContextCompat.getColor(itemView.context, R.color.bright_blue) else Color.BLACK)
            thumbData.hasBookMarks?.let {
                when (it[position]) {
                    true -> {
                        itemView.iv_pdfThumbGvItem_bookmark.visibility = View.VISIBLE
                    }
                    false -> {
                        itemView.iv_pdfThumbGvItem_bookmark.visibility = View.GONE
                    }
                }
            }
            when (!thumbData.isEditMode && thumbData.currentPage == position) {
                true -> {
                    itemView.view_pdfThumbGvItem_.visibility = View.VISIBLE
                }
                false -> {
                    itemView.view_pdfThumbGvItem_.visibility = View.GONE
                }
            }
            when (thumbData.isEditMode) {
                true -> {
                    itemView.cb_pdfThumbGvItem_.visibility = View.VISIBLE
                }
                false -> {
                    itemView.cb_pdfThumbGvItem_.visibility = View.GONE
                }
            }
        }

        fun setSize(width: Int, height: Int, padding: Int, density: Float) {
            if (width != itemView.rl_pdfThumbGvItem_.width) {
                val params = LinearLayout.LayoutParams(width, height)
                params.topMargin = (density * 4).toInt()
                params.leftMargin = padding
                params.rightMargin = padding
                itemView.rl_pdfThumbGvItem_.layoutParams = params
                itemView.iv_pdfThumbGvItem_.setPadding(1, 1, 1, 1)
            }
        }

        private fun loadThumbSync(thumbData: ThumbData, page: Int, thumbnailHandler: ThumbnailHandler) {
            stopLoadThumbSync()

            val bitmap = thumbData.pages.get(page)
            if  (null != bitmap) {
                itemView.iv_pdfThumbGvItem_.setImageBitmap(bitmap)
                itemView.iv_pdfThumbGvItem_.invalidate()
                itemView.pb_pdfThumbGvItem_.visibility = View.GONE
            } else {
                disposable = Observable.create<Bitmap> { emitter ->
                    val bitmap = thumbnailHandler.getPdfBitmap(page, 180, ThumbnailHandler.MODE_DAY, true)
                    thumbData.pages.put(page, bitmap)
                    emitter.onNext(bitmap)
                    emitter.onComplete()
                }
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({
                            itemView.iv_pdfThumbGvItem_.setImageBitmap(it)
                            itemView.iv_pdfThumbGvItem_.invalidate()
                            itemView.pb_pdfThumbGvItem_.visibility = View.GONE
                        }, {
                            it.printStackTrace()
                        })
            }
        }

        fun stopLoadThumbSync() {
            if (null != disposable && !disposable!!.isDisposed) {
                disposable?.dispose()
                disposable = null
            }
            itemView.iv_pdfThumbGvItem_.setImageBitmap(null)
            itemView.iv_pdfThumbGvItem_.invalidate()
            itemView.pb_pdfThumbGvItem_.visibility = View.VISIBLE
        }
    }

    fun setThumbData(thumbData: ThumbData) {
        data = thumbData
        notifyDataSetChanged()
    }

    override fun isLongPressDragEnabled(): Boolean {
        return data.isEditMode
    }

    override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
        val dragFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT or ItemTouchHelper.UP or ItemTouchHelper.DOWN
        val swipeFlags = 0
        return makeMovementFlags(dragFlags, swipeFlags)
    }

    override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
        notifyItemMoved(fromPosition, toPosition)
        handler.onPageMove(fromPosition,toPosition)
        return true
    }

    override fun onItemSwipe(position: Int) {
    }

    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        viewHolder.itemView.scaleX = 1.0f
        viewHolder.itemView.scaleY = 1.0f
        notifyDataSetChanged()
    }

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE && null != viewHolder) {
            viewHolder.itemView.scaleX = 0.7f
            viewHolder.itemView.scaleY = 0.7f
        }
    }

    interface PageMoveHandler{
        fun onPageMove(fromPage: Int, toPage: Int)
    }
}