package com.kdanmobile.reader.screen.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.RelativeLayout
import com.kdanmobile.reader.R
import com.kdanmobile.reader.screen.adapter.OutlineAdapter
import com.kdanmobile.reader.screen.handler.OutlineHandler
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
import kotlinx.android.synthetic.main.view_outline.view.*
import java.util.*

class OutlineView: RelativeLayout, LeftToolbarView {
    private var adapter: OutlineAdapter? = null
    private var pdfInfoHandler: PdfInfoHandler? = null
    private var outlineHandler: OutlineHandler? = null
    private var disposable: Disposable? = 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_outline, this)

        lv_viewPdfReaderOutline_.setOnItemClickListener { _, _, position, _ ->
            val item = adapter?.getItem(position)
            if (null != item) {
                pdfInfoHandler?.setCurrentPage(item.page)
            }
        }

    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        if (null != disposable && !disposable!!.isDisposed) {
            disposable?.dispose()
            disposable = null
        }
    }

    fun setHandlers(pdfInfoHandler: PdfInfoHandler, outlineHandler: OutlineHandler) {
        this.pdfInfoHandler = pdfInfoHandler
        this.outlineHandler = outlineHandler
        updateContent()
    }

    override fun updateContent() {
        disposable = Observable.create<OutlineAdapter> {
            val outlineItems = outlineHandler?.getOutline()?.clone() ?: arrayOf()
            Arrays.sort(outlineItems) { lhs, rhs -> if (lhs.page > rhs.page) 1 else if (lhs.page < rhs.page) -1 else 0 }
            val copyList = outlineItems.toList()
            it.onNext(OutlineAdapter(copyList))
            it.onComplete()
        }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    adapter = it
                    lv_viewPdfReaderOutline_.adapter = adapter
                }, {
                    it.printStackTrace()
                })
    }

    override fun onScrollToContent(pageIndex: Int, notify: Boolean) {

    }
}