import java.util.LinkedList;
import java.util.List;

public class EcgUtils
{
    /**
     * 获取频率
     *
     * @param data       所有的数据 20秒的数据
     * @param hz         采集的频率
     * @param max_num    波峰的代表值
     * @param min_num    波谷的代表值
     * @param check_time 一次计算的时间,会根据这个数据进行切割 [1-5秒的数据][2-6秒的数据][3-7秒的数据]
     * @param onResult   计算结果的回调
     * @return
     */
    public static void getRateCount(int[] data, int hz, int max_num, int min_num, int check_time, OnResult onResult)
    {
        if (data.length < hz * check_time) throw new RuntimeException("长度不足支持计算");

        List<int[]> datas = new LinkedList<>();

        for (int i = 0; i < data.length; i++)
        {
            int[] p_data = new int[hz * check_time];
            for (int j = 0; j < p_data.length; j++)
            {
                if (i + j < data.length)
                    p_data[j] = data[i + j];
                else
                    p_data[j] = 0;
            }
            datas.add(p_data);
            if (i + hz < data.length)
                i += hz;
            else
                i = data.length - 1;
        }
        for (int[] p_data : datas)
        {
            int first_index = -1;
            int last_index = p_data.length;
            int cha = 0;
            int count = 0;
            boolean findNext = true;
            for (int i = 0; i < p_data.length; i++)
            {
                int num = p_data[i];
                // 一次
                if (num >= max_num && findNext)
                {
                    count++;
                    findNext = false;

                    if (first_index == -1)
                    {
                        first_index = i;
                    }
                    last_index = i;
                } else if (num <= min_num && !findNext)
                {
                    findNext = true;
                }
            }

            if (onResult != null)
            {
                if (last_index - first_index == 0)
                {
                    cha = 1;
                } else
                {
                    cha = last_index - first_index;
                }
                System.out.print("hz=" + hz + " ");
                System.out.print("check_time=" + check_time + " ");
                System.out.print("count=" + count + " ");
                System.out.print("cha=" + cha + " ");
                onResult.onResult((60 * hz) * (count - 1) / cha);
            }
        }
    }

    interface OnResult
    {
	// 计算心率的结果
        void onResult(int value);
    }
}