package com.kdanmobile.kdan_others_library_for_android.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Shawn Lu on 2015/12/10.
 */
public class PercentageCircleView extends View {
    int width, height, left, top;
    float percent = 0f;
    Paint paint = new Paint();
    private int emptyColor = Color.LTGRAY;
    private int coverColor = 0xFF0077FD;

    public PercentageCircleView(Context context) {
        super(context);
        init();
    }

    public PercentageCircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PercentageCircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(8);
    }

    public void setPercent(float value) {
        percent = value;
        invalidate();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        width = right - left - getPaddingLeft() - getPaddingRight();
        height = bottom - top - getPaddingBottom() - getPaddingTop();
        this.left = getPaddingLeft();
        this.top = getPaddingTop();
    }

    @Override
    protected void onDraw(Canvas canvas) {

        if (width == 0 || height == 0) return;

        int radius = Math.min(width, height) / 2;
        paint.setColor(emptyColor);
        canvas.drawOval(new RectF(left, top, left + width, top + height), paint);
        paint.setColor(coverColor);
        canvas.drawArc(new RectF(left, top, left + width, top + height), -90, 360 * percent, false, paint);
        super.onDraw(canvas);
    }

    public void setEmptyColor(int emptyColor) {
        this.emptyColor = emptyColor;
        invalidate();
    }

    public void setCoverColor(int coverColor) {
        this.coverColor = coverColor;
        invalidate();
    }
}
