
package com.ydl.ydlcommon.view;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.RxImageTool;
import com.ydl.ydlcommon.R;

import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 头部广告栏
 * Created by softrice on 15/11/13.
 */
public class LoopViewPager extends RelativeLayout {

    //    @BindView(R.id.viewPager)
    DisallowParentTouchViewPager viewPager;

    //    @BindView(R.id.index_viewGroup)
    LinearLayout group;//放小点的View

    ImageView[] mImageViews;//装图片的数组
    ImageView[] tips;//装小点的数组

    boolean isInitFinish = false;

    int countImg = 0;
    private Timer mTimer;

    private boolean isNeedStop = false;
    private PagerAdapter adapter;

    public LoopViewPager(Context context) {
        super(context);
        inflate(context, R.layout.platform_head_view_pager, this);
        initView();
        init();
    }

    public LoopViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate(context, R.layout.platform_head_view_pager, this);
        initView();
        init();
    }

    public LoopViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        inflate(context, R.layout.platform_head_view_pager, this);
        initView();
        init();
    }

    private void initView() {
        viewPager = findViewById(R.id.viewPager);
        group = findViewById(R.id.index_viewGroup);
    }

    private int dcTime = 0;

    void init() {
        //计时,如果没有用户干预,每5秒进行vp操作,
        mTimer = new Timer(true);
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (isNeedStop) {
                    return;
                }
//                LogUtil.d("dcTime: " + dcTime);
                dcTime++;
                if (dcTime % 5 == 0) {
                    updateUI();
                }
            }
        }, 0, 1000);

    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            LogUtil.d("action down");
            timeDown = System.currentTimeMillis();
            viewPager.isClick = true;
        } else if (action == MotionEvent.ACTION_UP) {
            LogUtil.d("action up or cancel");
            timeUp = System.currentTimeMillis();
            viewPager.isClick = false;
        }
        return super.dispatchTouchEvent(ev);
    }

    private long timeDown;//用户按下的时间
    private long timeUp;//用户提起的时间

    void updateUI() {
//        LogUtil.d("updateUI");
        Observable.just(0)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    if (!isInitFinish)
                        return;
                    countImg++;
                    countImg %= adapter.getCount() == 0 ? 1 : adapter.getCount();
                    viewPager.setCurrentItem(countImg);
                });
    }

    public void fixTouch(FixRequestDisallowTouchEventPtrFrameLayout fixRequestDisallowTouchEventPtrFrameLayout) {
        viewPager.setNestParent(fixRequestDisallowTouchEventPtrFrameLayout);
    }

    public void setAdapter(PagerAdapter adapter) {
        this.adapter = adapter;
        isInitFinish = false;
        int count = adapter.getCount();
        tips = new ImageView[count];
        group.removeAllViews();
        //初始化小点
        for (int i = 0; i < count; i++) {
            ImageView imageView = new ImageView(getContext());
            int size = RxImageTool.dp2px(10);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(size, size));
            tips[i] = imageView;
            if (i == 0) {
                tips[i].setBackgroundResource(R.drawable.platform_tip_select);
            } else {
                tips[i].setBackgroundResource(R.drawable.platform_tip_unselect);
            }
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT));
            layoutParams.leftMargin = 5;
            layoutParams.rightMargin = 5;

            group.addView(imageView, layoutParams);
        }
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            //翻页成功
            @Override
            public void onPageSelected(int position) {
                countImg = position;
                setImageBackground(position % tips.length);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        isInitFinish = true;
        countImg = 0;
        viewPager.setAdapter(adapter);
    }


    /**
     * 改变图片
     */
    private void setImageBackground(int selectItems) {
        for (int i = 0; i < tips.length; i++) {
            if (i == selectItems) {
                tips[i].setBackgroundResource(R.drawable.platform_tip_select);
            } else {
                tips[i].setBackgroundResource(R.drawable.platform_tip_unselect);
            }
        }
    }


    public void startBanner() {
        isNeedStop = false;
    }

    public void stopBanner() {
        isNeedStop = true;
    }

    public void onCancel() {
        if (mTimer != null) {
            LogUtil.d("timer cancel");
            mTimer.cancel();
        }
    }
}
