package com.excelliance.open;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.LinearInterpolator;

import com.excelliance.lbui.R;

/**
 * Created by Wang Hujian on 2017/11/29.
 */
public class LoadingView extends View {
    private Paint mPaint;
    private Paint mPaintBack;
    private int mPaintColor = 0xFFFF007A;// 圆点颜色
    private float mPadding = 5;
    private float mCurrentAngle = 0f;
    private int mWidth = 0;
    private RectF mRectF;
    private ValueAnimator mAnimator;
    private int mChangeDotPos = 0;
    private int mDotCount = 3;
    private float mDotRadius = 5f;
    private float mAnimatedValue = 0f;
    private int mLoadingType;
    private Bitmap mBitmap;
    public static final int TYPE_CIRCLE = 0;
    public static final int TYPE_DOT = 1;
    public static final int TYPE_PIC = 2;
    private Resources mainRes = null;
    private Resources apkRes = null;
    private float mBitmapScale = 1f;
    private Context mContext;

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

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

    public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        mainRes = BwbxUI.getResources(context);
        apkRes = BwbxUI.getApkResources(context);
        int count = attrs.getAttributeCount();
        for(int i = 0;i < count;i++)
        {
            String name = attrs.getAttributeName(i);
            String value = attrs.getAttributeValue(i);
            if ("lebianColor".equals(name)){
                value = value.replace("#", "");
                mPaintColor = (int) Long.parseLong(value, 16);
            }
            if ("lebianType".equals(name)){
                mLoadingType = Integer.parseInt(value);
            }
        }
        init();
    }

    //初始化操作
    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        if (mLoadingType == TYPE_CIRCLE){
            mPaint.setStyle(Paint.Style.STROKE);
        }else {
            mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        }
        mPaint.setColor(mPaintColor);
        mPaint.setStrokeWidth(dip2px(mContext,3));

        mPaintBack=new Paint();
        mPaintBack.setAntiAlias(true);
        mPaintBack.setStyle(Paint.Style.STROKE);
        mPaintBack.setColor(Color.argb(100, 255, 255, 255));
        mPaintBack.setStrokeWidth(dip2px(mContext,3));

        initAnimatior();
        if (mLoadingType == TYPE_PIC){
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;
            int redId = apkRes.getIdentifier("lebian_coffee_normal", "drawable", mContext.getPackageName());
            if (redId > 0) {
                mBitmap = BitmapFactory.decodeResource(apkRes, redId);
            } else {
                mBitmap = BitmapFactory.decodeResource(mainRes, R.drawable.lebian_coffee_normal);
            }
            if (mBitmap.getWidth()>mBitmap.getHeight()){
                mBitmapScale = (float)mWidth / (float)mBitmap.getWidth();
            }else {
                mBitmapScale = (float)mWidth / (float)mBitmap.getHeight();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @SuppressLint("WrongConstant")
    private void initAnimatior() {
        mAnimator = ValueAnimator.ofFloat(0f, 1f);
        if (mLoadingType == TYPE_PIC){
            mAnimator.setDuration(1000);
        }else {
            mAnimator.setDuration(500);
        }
        mAnimator.setRepeatCount(-1);
        mAnimator.setRepeatMode(ValueAnimator.INFINITE);
        mAnimator.setInterpolator(new LinearInterpolator());

        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (mLoadingType == TYPE_CIRCLE || mLoadingType == TYPE_PIC){
                    mCurrentAngle = (float)animation.getAnimatedValue() * 360f;
                }else if (mLoadingType == TYPE_DOT){
                    mAnimatedValue = (float) animation.getAnimatedValue();
                    if (mAnimatedValue < 0.2f){
                        mAnimatedValue = 0.2f;
                    }
                }
                invalidate();
            }
        });
        mAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationRepeat(Animator animation) {
                super.onAnimationRepeat(animation);
                if (mLoadingType == TYPE_DOT){
                    mChangeDotPos++;
                }
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getMeasuredWidth() > getHeight())
            mWidth = getMeasuredHeight();
        else
            mWidth = getMeasuredWidth();
        mPadding = getPaddingTop();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mLoadingType == TYPE_CIRCLE){
            drawCircle(canvas);
        }else if (mLoadingType == TYPE_DOT){
            drawDot(canvas);
        }else {
            drawBitmap(canvas);
        }

    }

    private void drawCircle(Canvas canvas) {
        canvas.drawCircle(mWidth/2,mWidth/2,mWidth / 2 - mPadding,mPaintBack);
        if (mRectF == null) {
            mRectF = new RectF(mPadding,mPadding,mWidth-mPadding,mWidth-mPadding);
        }
        canvas.drawArc(mRectF,mCurrentAngle,100,false,mPaint);
    }

    private void drawDot(Canvas canvas){
        float circleX = mWidth / mDotCount;
        for (int i=0;i<mDotCount;i++){
            if (i == mChangeDotPos%mDotCount){
                canvas.drawCircle(i*circleX+circleX/2,mWidth/2,mDotRadius*mAnimatedValue,mPaint);
            }else {
                canvas.drawCircle(i*circleX+circleX/2,mWidth/2,mDotRadius,mPaint);
            }
        }
    }

    private void drawBitmap(Canvas canvas) {
        Matrix matrix = new Matrix();
        int offsetX = mBitmap.getWidth() / 2;
        int offsetY = mBitmap.getHeight() / 2;
        matrix.postTranslate(-offsetX, -offsetY);
        matrix.postRotate(mCurrentAngle);
        matrix.postTranslate(mWidth/2, mWidth/2);
        canvas.drawBitmap(mBitmap, matrix, mPaint);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        startAnimation();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void startAnimation() {
        mAnimator.start();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void stopAnimation() {
        mAnimator.end();
    }

    //销毁页面时停止动画
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopAnimation();
    }

    //dip转化为px
    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}