package com.pan_american.android.util

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.core.content.ContextCompat
import com.pan_american.android.R

internal class SearchView(context: Context, attrs: AttributeSet) :
    androidx.appcompat.widget.AppCompatEditText(context, attrs) {
    private var searchSize = 0f
    private var textSize = 0f
    private var textColor = -0x1000000
    private var drawable: Drawable? = null
    private var paint: Paint? = null

    init {
        initResource(context, attrs)
        initPaint()
    }

    private fun initResource(context: Context, attrs: AttributeSet) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SearchView)
        val density = context.resources.displayMetrics.density
        searchSize = typedArray.getDimension(R.styleable.SearchView_imageWidth, 18 * density + 0.5f)
        textColor = typedArray.getColor(R.styleable.SearchView_textColor, -0x7b7b7c)
        textSize = typedArray.getDimension(R.styleable.SearchView_textSize, 16 * density + 0.5f)
        typedArray.recycle()
    }

    private fun initPaint() {
        paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint!!.color = textColor
        paint!!.textSize = textSize
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        drawSearchIcon(canvas)
    }

    private fun drawSearchIcon(canvas: Canvas) {
        if (this.text.toString().isEmpty()) {
            val textWidth = paint!!.measureText(resources.getString(R.string.search))
            val textHeight = getFontLeading(paint)
            val dx = (width - searchSize - textWidth - 8) / 2
            val dy = (height - searchSize) / 2
            canvas.save()
            canvas.translate(scrollX + dx, scrollY + dy)
            if (drawable != null) {
                drawable!!.draw(canvas)
            }
            canvas.drawText(
                resources.getString(R.string.search),
                scrollX + searchSize + 8,
                scrollY + (height - (height - textHeight) / 2) - paint!!.fontMetrics.bottom - dy,
                paint!!
            )
            canvas.restore()
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        if (drawable == null) {
            drawable = ContextCompat.getDrawable(context, R.mipmap.icon_search)
            drawable!!.setBounds(0, 0, searchSize.toInt(), searchSize.toInt())
        }
    }

    override fun onDetachedFromWindow() {
        if (drawable != null) {
            drawable!!.callback = null
            drawable = null
        }
        super.onDetachedFromWindow()
    }

    private fun getFontLeading(paint: Paint?): Float {
        val fontMetrics = paint!!.fontMetrics
        return fontMetrics.bottom - fontMetrics.top
    }
}