package com.yidianling.uikit.custom.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.VectorDrawable;

/**
 * @author harvie
 * 自定义半圆斜角drawable
 */
@SuppressLint("NewApi")
public class HalfCircleDrawable extends VectorDrawable {

    private Context context;

    private int width;
    private int height;

    //左上角节点x坐标
    private int leftTopX;
    //圆弧x轴半径
    private int circleRadiusX;
    //右上x坐标
    private int rightTopX;
    //右下角x轴坐标
    private int rightBottomX;

    private int defaultColor;

    private boolean reverse; //是否反转

    /**
     *
     * @param context
     * @param reverse 是否反转，默认圆弧居右侧
     * @param mColor 画笔颜色
     */
    public HalfCircleDrawable(Context context, boolean reverse, int mColor) {
        this.context = context;
        this.defaultColor = mColor;
        this.reverse = reverse;
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        super.onBoundsChange(bounds);
        width = bounds.right;
        height = bounds.bottom;

        leftTopX = dp2px(8f);
        circleRadiusX = height/2;
        rightTopX = width-circleRadiusX;
        rightBottomX = leftTopX;
    }

    @Override
    public void draw( Canvas canvas) {

        if (reverse){
            canvas.rotate(180,width/2,height/2);
        }

        Paint paint = new Paint();
        paint.setColor(defaultColor);
        paint.setAntiAlias(true);

        Path path = new Path();
        path.moveTo(leftTopX,0);
        path.lineTo(rightTopX,0);
        RectF rectF = new RectF();
        rectF.left = rightTopX-circleRadiusX;
        rectF.top = 0;
        rectF.right = rightTopX+circleRadiusX;
        rectF.bottom = height;
        path.arcTo(rectF,270,180);
        path.lineTo(0,height);
        path.lineTo(leftTopX,0);
        path.close();

        canvas.drawPath(path,paint);

        if (reverse){
            canvas.rotate(180,width/2,height/2);
        }
    }

    @Override
    public void setAlpha(int alpha) {

    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {

    }

    @SuppressLint("WrongConstant")
    @Override
    public int getOpacity() {
        return 5;
    }

    private int dp2px(float dp){
        float density = context.getResources().getDisplayMetrics().density;
        return (int)(dp*density);
    }

}
