package com.kdanmobile.reader.screen.view

import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.RelativeLayout
import com.kdanmobile.reader.R
import com.kdanmobile.reader.screen.adapter.ThumbnailAdapter
import com.kdanmobile.reader.screen.handler.PdfInfoHandler
import com.kdanmobile.reader.screen.handler.ThumbnailHandler
import com.kdanmobile.reader.widget.drag.OnRecyclerItemClickListener
import kotlinx.android.synthetic.main.view_thumbnail.view.*

class ThumbnailView: RelativeLayout, LeftToolbarView {
    private var adapter: ThumbnailAdapter? = null
    private var currentPage = 0
    private var pdfInfoHandler: PdfInfoHandler? = null

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

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

    constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr) {
        initView()
    }

    private fun initView() {
        LayoutInflater.from(context).inflate(R.layout.view_thumbnail, this)
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = LinearLayoutManager.VERTICAL

        id_km_thumb_recycler.setHasFixedSize(true)
        id_km_thumb_recycler.layoutManager = layoutManager
        id_km_thumb_recycler.layoutManager = LinearLayoutManager(context)
        id_km_thumb_recycler.addOnItemTouchListener(object : OnRecyclerItemClickListener(id_km_thumb_recycler) {
            override fun onItemClick(viewHolder: RecyclerView.ViewHolder) {
                onScrollToContent(viewHolder.adapterPosition, true)
                pdfInfoHandler?.setCurrentPage(viewHolder.adapterPosition)
            }

            override fun onItemLongClick(viewHolder: RecyclerView.ViewHolder) {

            }
        })
    }

    fun setHandlers(pdfInfoHandler: PdfInfoHandler, thumbnailHandler: ThumbnailHandler) {
        this.pdfInfoHandler = pdfInfoHandler

        adapter = ThumbnailAdapter(pdfInfoHandler, thumbnailHandler)
        id_km_thumb_recycler.adapter = adapter
        currentPage = pdfInfoHandler.getCurrentPage()
        onScrollToContent(currentPage, true)
    }

    override fun updateContent() {
        adapter?.notifyDataSetChanged()
    }

    override fun onScrollToContent(pageIndex: Int, notify: Boolean) {
        val position = Math.min(adapter?.itemCount ?:0, Math.max(0, pageIndex))
        currentPage = position

        if (notify) {
            adapter?.setCurrentPage(position)
        }

        if (null != id_km_thumb_recycler) {
            id_km_thumb_recycler.scrollToPosition(position)
        }
    }
}