package com.kdanmobile.reader.screen.reader.mediabox.signature

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.support.v4.util.LruCache
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.kdanmobile.reader.R
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_media_box_item_signature.view.*

class SignatureAdapter(private val context: Context, private var signaturePaths: ArrayList<String>): RecyclerView.Adapter<SignatureViewHolder>() {

    companion object {
        val maxMemory = Runtime.getRuntime().maxMemory() / 16

        val mMemoryCache: LruCache<String, Bitmap> = object: LruCache<String, Bitmap>(maxMemory.toInt()) {
            override fun sizeOf(key: String, value: Bitmap): Int {
                return value.byteCount
            }
        }
    }

    private var onSignatureClickListener: OnSignatureClickListener? = null
    private var onSignatureRemoveListener: OnSignatureRemoveListener? = null

    override fun onBindViewHolder(holder: SignatureViewHolder, position: Int) {
        holder.filename = signaturePaths[position]
        holder.loadThumbSync()
        holder.ivSignature.setOnClickListener {
            onSignatureClickListener?.onSignatureClick(holder.filename)
        }
        holder.btnClose.setOnClickListener {
            onSignatureRemoveListener?.onSignatureRemove(signaturePaths[holder.adapterPosition])
        }
    }

    override fun getItemCount(): Int {
        return signaturePaths.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SignatureViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.view_media_box_item_signature, null)
        return SignatureViewHolder(view)
    }

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

    fun setOnSignatureClickListener(onSignatureClickListener: OnSignatureClickListener?) {
        this.onSignatureClickListener = onSignatureClickListener
    }

    fun setOnSignatureRemoveListener(onSignatureRemoveListener: OnSignatureRemoveListener?) {
        this.onSignatureRemoveListener = onSignatureRemoveListener
    }
}

class SignatureViewHolder(view: View): RecyclerView.ViewHolder(view) {
    val ivSignature: ImageView = view.iv_signature
    val btnClose: View = view.btn_close
    var filename: String = ""
    private var disposable: Disposable? = null

    fun loadThumbSync() {
        stopLoadThumbSync()

        disposable = Observable.create<Bitmap> { emitter ->
            val bitmap: Bitmap
            val value = SignatureAdapter.mMemoryCache[filename]
            if (null != value) {
                bitmap = value
            } else {
                bitmap = BitmapFactory.decodeFile(filename)
                SignatureAdapter.mMemoryCache.put(filename, bitmap)
            }
            emitter.onNext(bitmap)
            emitter.onComplete()
        }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    ivSignature.setImageBitmap(it)
                    ivSignature.invalidate()
                    setScaleTypeFixLeft(ivSignature)
                }, {
                    it.printStackTrace()
                })
    }

    private fun setScaleTypeFixLeft(imageView: ImageView) {

        val drawableWidth = imageView.drawable.intrinsicWidth
        val drawableHeight = imageView.drawable.intrinsicHeight
        if (drawableWidth != 0 && drawableHeight != 0) {
            val matrix = Matrix()
            val viewWidth = imageView.width - imageView.paddingLeft - imageView.paddingRight
            val viewHeight = imageView.height - imageView.paddingTop - imageView.paddingBottom
            val scaleRatioX = viewWidth.toFloat() / drawableWidth
            val scaleRatioY = viewHeight.toFloat() / drawableHeight
            val scaleFactor = Math.min(scaleRatioX, scaleRatioY)
            matrix.setScale(scaleFactor, scaleFactor)
            matrix.postTranslate(0f, (viewHeight - drawableHeight * scaleFactor) * 0.5f)
            imageView.imageMatrix = matrix
        }
    }

    internal fun stopLoadThumbSync() {
        if (null != disposable && !disposable!!.isDisposed) {
            disposable?.dispose()
            disposable = null
            ivSignature.setImageBitmap(null)
            ivSignature.invalidate()
        }
    }
}