package com.secspace.lib.common.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;

import com.secspace.lib.common.R;
import com.secspace.lib.common.utils.DensityUtil;

/**
 * Created by cyw_m on 2018/4/9.
 */

public class LoopProgressBar extends View {

    //短线的颜色，我们也可以开放一个setColor接口设置颜色
    private int color;
    //绘制短线的画笔
    private Paint paint;
    //短线之间间隔
    private float space;
    //短线的宽度
    private float lineWidth;
    //绘制短线的起点
    private int startX;

    private boolean processing;

    public LoopProgressBar(Context context) {
        this(context, null);
    }

    public LoopProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoopProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LoopProgressBar);
        if (ta != null) {
            color = ta.getColor(R.styleable.LoopProgressBar_lineColor, Color.GREEN);
            space = ta.getDimension(R.styleable.LoopProgressBar_space, DensityUtil.dip2px(getContext(), 20));
            lineWidth = ta.getDimension(R.styleable.LoopProgressBar_lineWidth, DensityUtil.dip2px(getContext(), 50));
        }
        if (ta != null) {
            ta.recycle();
        }
        paint = new Paint();
        paint.setColor(color);
        paint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //整个控件的高度和宽度当执行到onDraw时已经layout了宽高早已经测量完成
        int w = getMeasuredWidth();
        int h = getMeasuredHeight();
        int delta = 10;
        paint.setColor(color);
        paint.setStrokeWidth(h);
        if (!processing) {
            paint.setColor(ContextCompat.getColor(getContext(), R.color.base_secondary_text));
            canvas.drawLine(0, 0, w, h, paint);
            return;
        }
        //startX从0开始每次递增delta,当第一根短线（最右边一根）的右端到达空间末尾时从0重新开始绘制，形成循环
        if (startX >= w + (lineWidth + space) - (w % (lineWidth + space))) {
            startX = 0;
        } else {
            startX += delta;
        }
        float start = startX;
        //绘制短线
        while (start < w) {
            canvas.drawLine(start, 5, start + lineWidth, 5, paint);
            start += (lineWidth + space);
        }
        start = startX - space - lineWidth;
        //从左边进入的短线
        while (start >= -lineWidth) {
            canvas.drawLine(start, 5, start + lineWidth, 5, paint);
            start -= (lineWidth + space);
        }
        postInvalidateDelayed(60);
    }

    public void start() {
        processing = true;
        postInvalidate();
    }

    public void stop() {
        processing = false;
        postInvalidate();
    }
}