package com.kdanmobile.reader.test

import android.content.Context
import android.graphics.Point
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import com.kdanmobile.kmpdfkit.manager.KMPDFFactory
import com.kdanmobile.kmpdfkit.pdfcommon.FilePicker
import com.kdanmobile.kmpdfkit.pdfcommon.KMPDFPageAdapter
import com.kdanmobile.reader.R

open class MyPageAdapter(
        protected val context: Context,
        private val filePickerSupport: FilePicker.FilePickerSupport,
        private val kmpdfFactory: KMPDFFactory,
        protected val adPageHelper: AdPageHelper? = null
): KMPDFPageAdapter(context, filePickerSupport, kmpdfFactory) {

    override fun getCount(): Int {
        return adPageHelper?.getPageCount() ?: 0
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val isAdPage = adPageHelper?.isAdPage(position) ?: false
        val page = adPageHelper?.convertToRawPageIndex(position) ?: 0
        val pageView = if (convertView == null) {
            MyPageView(context, filePickerSupport, kmpdfFactory, Point(parent?.width ?: 0, parent?.height ?: 0), isAdPage)
        } else {
            convertView as MyPageView
        }
        when (isAdPage) {
            true -> {
                pageView.apply {
                    adHeight = MyPageView.DEFAULT_AD_HEIGHT
                    setupViewContent(position, this)
                    isAdShowing = adPageHelper?.isAdVisible(position) ?: false
                }
            }
            false -> {
                super.getView(page, pageView, parent)
            }
        }
        return pageView
    }

    open fun setupViewContent(position: Int, pageView: MyPageView) {
        val imageView = ImageView(context)
        imageView.setBackgroundResource(R.drawable.background)
        imageView.scaleType = ImageView.ScaleType.FIT_CENTER
        pageView.layout.addView(imageView)

        imageView.setOnClickListener {
            Toast.makeText(context, "[$position][${pageView.page}] TEST", Toast.LENGTH_SHORT).show()
        }
    }
}