package com.kdanmobile.reader.screen.adapter

import android.graphics.Bitmap
import android.support.v4.content.ContextCompat
import android.support.v4.util.LruCache
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import com.kdanmobile.reader.R
import com.kdanmobile.reader.screen.handler.ThumbnailHandler
import com.kdanmobile.reader.screen.adapter.ThumbnailAdapter.ThumbnailViewHolder
import com.kdanmobile.reader.screen.handler.PdfInfoHandler
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

class ThumbnailAdapter(private val pdfInfoHandler: PdfInfoHandler, private val thumbnailHandler: ThumbnailHandler): RecyclerView.Adapter<ThumbnailViewHolder>() {
    private var currentPage = 0

    init {
        this.currentPage = pdfInfoHandler.getCurrentPage()
    }

    fun setCurrentPage(currentPage: Int) {
        val oldCurrentPage = this.currentPage
        this.currentPage = currentPage
        notifyItemChanged(oldCurrentPage, false)
        notifyItemChanged(currentPage, true)
    }

    fun clearMapSoftNotify() {
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return pdfInfoHandler.getPdfPageCount()
    }

    override fun onBindViewHolder(holder: ThumbnailViewHolder, position: Int) {
        holder.page.text = (holder.adapterPosition + 1).toString()
        holder.onShowBorder(currentPage == holder.adapterPosition)
        holder.loadThumbSync()
    }

    override fun onBindViewHolder(holder: ThumbnailViewHolder, position: Int, payloads: List<Any>) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position)
        } else {
            for (obj in payloads) {
                if (obj is Boolean) {
                    holder.onShowBorder(obj)
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ThumbnailViewHolder {
        val view = View.inflate(parent.context, R.layout.item_thumbnail, null)
        return ThumbnailViewHolder(parent, view)
    }

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

    inner class ThumbnailViewHolder(parent: ViewGroup, itemView: View): ViewHolder(itemView) {
        private val thumb: ImageView
        internal val page: TextView
        private val border: View
        private val progress: ProgressBar
        private var disposable: Disposable? = null

        init {
            val idReaderThumbFl = itemView.findViewById<View>(R.id.id_reader_thumb_fl) as FrameLayout
            val params = RecyclerView.LayoutParams(parent.measuredWidth - 20, (parent.measuredWidth - 20) * 9 / 7)
            params.setMargins(10, 5, 10, 5)
            idReaderThumbFl.layoutParams = params

            thumb = itemView.findViewById(R.id.iv_fragmentPdfReaderThumbLvItem_) as ImageView
            page = itemView.findViewById(R.id.tv_fragmentPdfReaderThumbLvItem_page) as TextView
            border = itemView.findViewById(R.id.v_pdfThumbGvItem_)
            progress = itemView.findViewById(R.id.pb_fragmentPdfReaderThumbLvItem_) as ProgressBar
        }

        internal fun onShowBorder(isShow: Boolean) {
            border.visibility = if (isShow) View.VISIBLE else View.GONE
            page.setBackgroundColor(ContextCompat.getColor(itemView.context, if (isShow) R.color.reader_thumbnail_background_selected else R.color.reader_thumbnail_background_normal))
            page.setTextColor(ContextCompat.getColor(itemView.context, if (isShow) R.color.reader_thumbnail_page_selected else R.color.reader_thumbnail_page_normal))
        }

        internal fun loadThumbSync() {
            stopLoadThumbSync()

            disposable = Observable.create<Bitmap> { emitter ->
                val bitmap = thumbnailHandler.getPdfBitmap(adapterPosition, 180, ThumbnailHandler.MODE_DAY, true)
                emitter.onNext(bitmap)
                emitter.onComplete()
            }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        thumb.setImageBitmap(it)
                        thumb.invalidate()
                        progress.visibility = View.GONE
                    }, {
                        it.printStackTrace()
                    })
        }

        internal fun stopLoadThumbSync() {
            if (null != disposable && !disposable!!.isDisposed) {
                disposable?.dispose()
                disposable = null
            }
            thumb.setImageBitmap(null)
            thumb.invalidate()
            progress.visibility = View.VISIBLE
        }
    }
}
