package com.excelliance.open;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.widget.FrameLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 轮播图
 */
@SuppressLint("NewApi")
public class SwitchView extends FrameLayout {
    public static final String TAG = "SwitchView";
    private List<AdaptiveImageView.ImageItem> mImages = new ArrayList<>();
    private Context mContext;
    private Handler handler = new Handler(Looper.getMainLooper());
    private int count = 0;
    private long time = 5000;//图片显示的时长
    private long aniTime = 1500;//淡入淡出显示的时长
    private long noAniTime = 0;
    private AdaptiveImageView mTopImageView;
    private AdaptiveImageView mBottomImageView;
    private LbUiWindowManager mLbWindowManager;
    public static final String BG_NAME = "lebian_main_background_normal";


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

    public SwitchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Log.d(TAG, "NewSwitchView");
        this.mContext = context;
        Resources mainRes = BwbxUI.getResources(context);
        Resources apkRes = BwbxUI.getApkResources(context);
        mLbWindowManager = LbUiWindowManager.getInstance(mContext);
        try {
            //优先初始化apk内部图片资源
            if (!initResourceImage(apkRes)) {
                //初始化新版本的图片资源
                if (!initNewVersionImage()) {
                    //初始化jar包的资源
                    if (!initResourceImage(mainRes)) {
                        Log.d(TAG, "no background image");
                    }
                }
            }
            //开始轮播
            startCyclePlayImage();
        } catch (Throwable throwable) {
            Log.e(TAG, throwable.getMessage());
            //发生崩溃的时候，加载一张默认图片
            AdaptiveImageView.ImageItem imageItem;
            try {
                AdaptiveImageView iv = new AdaptiveImageView(context);
                int v = apkRes.getIdentifier(BG_NAME, "drawable", context.getPackageName());
                if (v > 0) {
                    imageItem = new AdaptiveImageView.ImageItem(apkRes, v);
                } else {
                    v = mainRes.getIdentifier(BG_NAME, "drawable", context.getPackageName());
                    imageItem = new AdaptiveImageView.ImageItem(mainRes, v);
                }
                addView(iv, new LayoutParams(mLbWindowManager.getScreenWidth(mContext), mLbWindowManager.getScreenHeight(mContext)));
                iv.setImageItemShow(imageItem);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    private void startCyclePlayImage() {
        removeAllViews();
        if (!mImages.isEmpty()) {
            if (mTopImageView == null) {
                mTopImageView = new AdaptiveImageView(mContext);
                LayoutParams layoutParams = new LayoutParams(mLbWindowManager.getScreenWidth(mContext), mLbWindowManager.getScreenHeight(mContext));
                addView(mTopImageView, layoutParams);
            }
            //图片超过两个，多加一个ImageView，目的为了动画效果
            if (mImages.size() > 1 && mBottomImageView == null) {
                mBottomImageView = new AdaptiveImageView(mContext);
                LayoutParams layoutParams = new LayoutParams(mLbWindowManager.getScreenWidth(mContext), mLbWindowManager.getScreenHeight(mContext));
                addView(mBottomImageView, layoutParams);
            }
            //开始轮播动画
            startImageAnim();
        } else {
            Log.d(TAG, "image is empty");
        }
    }

    private void startImageAnim() {
        final int size = mImages.size();
        Log.d(TAG, "startImageAnim image size :" + size);
        count = 0;
        handler.post(new Runnable() {
            @Override
            public void run() {
                final int index = count % size;
                //第一张不需要动画效果
                if (count == 0) {
                    if (mTopImageView != null) {
                        mTopImageView.setImageItemShow(mImages.get(0));
                    }
                } else {
                    //轮播到最后一张了，从第一张开始轮播
                    if (index >= size) {
                        doInOutAnimation(0);
                    } else {
                        doInOutAnimation(index);
                    }
                }
                count++;
                handler.postDelayed(this, time);
            }
        });
    }

    private void doInOutAnimation(int index) {
        if (mBottomImageView != null && mTopImageView != null) {
            if (count % 2 == 0) {
                mTopImageView.setImageItemShow(mImages.get(index));
                mBottomImageView.startAnimation(createOutAwayAnim());
                mTopImageView.startAnimation(createOutNearAnim());

            } else {
                mBottomImageView.setImageItemShow(mImages.get(index));
                mTopImageView.startAnimation(createOutAwayAnim());
                mBottomImageView.startAnimation(createOutNearAnim());
            }
        }
    }


    /**
     * 根据source获取对应的source id列表
     */
    private boolean initResourceImage(Resources res) {
        int sourceId = getImageSourceId(res, BG_NAME);
        if (sourceId > 0) {
            mImages.add(new AdaptiveImageView.ImageItem(res, sourceId));
        }
        int j = 0;
        while (true) {
            sourceId = getImageSourceId(res, BG_NAME + "_" + (j));
            if (sourceId > 0) {
                mImages.add(new AdaptiveImageView.ImageItem(res, sourceId));
            } else {
                if (j > 10) {
                    break;
                }
            }
            j++;
        }
        return !mImages.isEmpty();
    }

    /**
     * 新版本image不存放到app中，通过制定path获取
     */
    private boolean initNewVersionImage() {
        int i = 0;
        while (true) {
            String path = getNewVersionImagePath(i);
            if (path == null) {
                if (i > 10) {
                    break;
                }
            } else {
                mImages.add(new AdaptiveImageView.ImageItem(path));
            }
            i++;
        }
        return !mImages.isEmpty();
    }


    //创建一个淡出的动画
    public Animation createOutAwayAnim() {
        AnimationSet ret = new AnimationSet(false);
        Animation anim = new AlphaAnimation(1f, 0f);//淡出动画
        if (BwbxUI.getGlobalBoolean(mContext, "USE_ANIMAL_WHEN_SWITCH_VIEW", true)) {
            anim.setDuration(aniTime);
        } else {
            anim.setDuration(noAniTime);
        }
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        ret.addAnimation(anim);
        ret.setFillAfter(true);
        return ret;
    }

    //创建一个淡入的动画
    public Animation createOutNearAnim() {
        AnimationSet ret = new AnimationSet(false);
        Animation anim = new AlphaAnimation(0f, 1f);//淡入动画
        if (BwbxUI.getGlobalBoolean(mContext, "USE_ANIMAL_WHEN_SWITCH_VIEW", true)) {
            anim.setDuration(aniTime);
        } else {
            anim.setDuration(noAniTime);
        }
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        ret.addAnimation(anim);
        ret.setFillAfter(true);
        return ret;
    }


    private int getImageSourceId(Resources res, String bgName) {
        return res.getIdentifier(bgName, "drawable", mContext.getPackageName());
    }


    private String getNewVersionImagePath(int index) {
        String path = mContext.getApplicationInfo().dataDir + "/lebian/";
        String name = BG_NAME + "_" + index + ".jpg";
        File file = new File(path + name);
        if (file.exists()) {
            return file.getAbsolutePath();
        } else {
            return null;
        }
    }
}