package com.gh.gamecenter.common.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.gh.gamecenter.common.R
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor


class DashLineView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
    // 虚线颜色
    private var dashColor = R.color.ui_divider.toColor(context)

    // 虚线粗细
    private var strokeWidth = 1F.dip2px()

    // 虚线宽度
    private var dashWidth = 4F.dip2px()

    // 虚线隔断宽度
    private var dashGapWidth = 4F.dip2px()

    // 虚线圆角
    private var dashRadius = 0.5F.dip2px()

    private var paint: Paint? = null
    private var path: Path? = null

    init {
        obtainAttributes(context, attrs)
        initView()
    }

    private fun obtainAttributes(context: Context, attrs: AttributeSet?) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.DashLineView)
        dashColor = ta.getColor(R.styleable.DashLineView_dash_line_color, R.color.ui_divider.toColor(context))
        strokeWidth = ta.getDimensionPixelSize(R.styleable.DashLineView_dash_line_stroke_width, 1F.dip2px())
        dashWidth = ta.getDimensionPixelSize(R.styleable.DashLineView_dash_width, 4F.dip2px())
        dashGapWidth = ta.getDimensionPixelSize(R.styleable.DashLineView_dash_gap_width, 4F.dip2px())
        dashRadius = ta.getDimensionPixelSize(R.styleable.DashLineView_dash_radius, 0.5F.dip2px())
        ta.recycle()
    }

    private fun initView() {
        if (isInEditMode) {
            return
        }

        paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint?.style = Paint.Style.STROKE
        path = Path()

        val roundRectF = RectF(0F, 0F, dashWidth.toFloat(), strokeWidth.toFloat())
        path?.addRoundRect(roundRectF, dashRadius.toFloat(), dashRadius.toFloat(), Path.Direction.CW)

        paint?.color = dashColor
        paint?.strokeWidth = strokeWidth.toFloat()
        paint?.setPathEffect(
            PathDashPathEffect(
                path,
                (dashWidth + dashGapWidth).toFloat(),
                0F,
                PathDashPathEffect.Style.TRANSLATE
            )
        )
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(measuredWidth, measuredHeight)
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        val centerY = height / 2F
        path?.reset()
        path?.moveTo(0F, centerY)
        path?.lineTo(width.toFloat(), centerY)
        canvas.drawPath(path!!, paint!!)
    }

    fun setDashLineColor(color: Int) {
        dashColor = color
        initView()
        invalidate()
    }
}