package com.xunao.effectdemo.activity;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.xunao.effectdemo.R;
import com.xunao.effectdemo.adapter.RolePlayAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class RolePlayActivity extends Activity {
    private static final String TAG = "RolePlayActivity";

    private Button btnStart;
    private RecyclerView rvMarquee;
    private RolePlayAdapter rolePlayAdapter;
    private List<String> roleList = new ArrayList<>();
    private String currentRole;  // 拿到随机选中的角色

    // 跑马灯
    private boolean isGameRunning = false; //是否处于转动
    private boolean isTryToStop = false;//是否增速/减速

    private int currentTotal = 0;

    private static final int DEFAULT_SPEED = 150; //默认/最慢速度
    private static final int MIN_SPEED = 50;//最快速度
    private int currentSpeed = DEFAULT_SPEED;//当前速度

    Timer timer = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_role_play);
        initView();
    }

    private void initView(){
        btnStart = findViewById(R.id.btn_start);
        btnStart.setOnClickListener(v -> {
            int stayIndex = new Random().nextInt(roleList.size());
            Log.i(TAG, "stayIndex:" + stayIndex);
            startGame(stayIndex);
        });
        rvMarquee = findViewById(R.id.rv_marquee);
        ((SimpleItemAnimator) Objects.requireNonNull(rvMarquee.getItemAnimator())).setSupportsChangeAnimations(false);

        // 设置横向布局
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false){
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        rvMarquee.setLayoutManager(linearLayoutManager);

        roleList.add("角色1");
        roleList.add("角色2");
        roleList.add("角色3");
        roleList.add("角色4");
        roleList.add("角色5");
        roleList.add("角色6");

        rolePlayAdapter = new RolePlayAdapter(roleList, this);
        rvMarquee.setAdapter(rolePlayAdapter);
    }

    //开始抽奖
    public void startGame(final int stayIndex) {
        if (isGameRunning) {  //运动中
            return;
        }
        isGameRunning = true;
        isTryToStop = false;
        currentSpeed = DEFAULT_SPEED;
        new Thread(() -> {
            while (isGameRunning) {
                try {
                    Thread.sleep(getInterruptTime());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 防止线程多走了一次
                if (!isGameRunning) {
                    return;
                }
                // 改变高亮项的索引
                runOnUiThread(() -> rolePlayAdapter.changeIndex());
                Log.i(TAG, "到" + roleList.get(rolePlayAdapter.getCurrentIndex()) + "--" + rolePlayAdapter.getCurrentIndex());

                //减速&&速度达到最小&&当前view为指定view——停止
                if (isTryToStop && currentSpeed == DEFAULT_SPEED && stayIndex == rolePlayAdapter.getCurrentIndex()) {
                    isGameRunning = false;
                    Log.i(TAG, "结束：角色为" + roleList.get(rolePlayAdapter.getCurrentIndex()) + "--" + rolePlayAdapter.getCurrentIndex());
//                        listener.onShop(currentIndex);
                    currentRole = roleList.get(rolePlayAdapter.getCurrentIndex());
                }
            }
        }).start();

        //2秒后开始减速
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                tryToStop();
            }
        }, 2000);
    }

    //改变加速状态
    public void tryToStop() {
        isTryToStop = true;
    }

    //获取sleep时间，即转盘运动速度，越小即越快。
    private long getInterruptTime() {
        currentTotal++;
        if (isTryToStop) {//减速直至恢复为默认速度
            currentSpeed += 10;
            if (currentSpeed > DEFAULT_SPEED) {
                currentSpeed = DEFAULT_SPEED;
            }
        } else {//增速直至最快速度
            //第一圈不做加速
            if (currentTotal / roleList.size() > 0) {
                currentSpeed -= 10;
            }
            if (currentSpeed < MIN_SPEED) {
                currentSpeed = MIN_SPEED;
            }
        }
        return currentSpeed;
    }
}