import 'dart:collection';
import 'dart:ui';

import 'package:flutter/scheduler.dart';

/// 单位换算
int byte2MB(int bytes) {
  return (bytes / 1024 / 1024).round();
}

// 需监听fps时注册
void startFPSListener() {
  SchedulerBinding.instance.addTimingsCallback(_onReportTimings);
}

// 不需监听时移除
void stopFPSListener() {
  SchedulerBinding.instance.removeTimingsCallback(_onReportTimings);
}

const maxframes = 100; // 100 帧足够了，对于 60 fps 来说
final lastFrames = ListQueue<FrameTiming>(maxframes);
const refreshRate = 60;
const frameInterval =
    Duration(microseconds: Duration.microsecondsPerSecond ~/ 60);

void _onReportTimings(List<FrameTiming> timings) {
  // 把 Queue 当作堆栈用
  for (FrameTiming timing in timings) {
    lastFrames.addFirst(timing);
  }

  // 只保留 maxframes
  while (lastFrames.length > maxframes) {
    lastFrames.removeLast();
  }
}

double get getScreenFPS {
  var lastFramesSet = <FrameTiming>[];
  for (FrameTiming timing in lastFrames) {
    if (lastFramesSet.isEmpty) {
      lastFramesSet.add(timing);
    } else {
      var lastStart =
          lastFramesSet.last.timestampInMicroseconds(FramePhase.buildStart);
      if (lastStart - timing.timestampInMicroseconds(FramePhase.rasterFinish) >
          (frameInterval.inMicroseconds * 2)) {
        // in different set
        break;
      }
      lastFramesSet.add(timing);
    }
  }
  var framesCount = lastFramesSet.length;
  var costCount = lastFramesSet.map((t) {
    // 耗时超过 frameInterval 会导致丢帧
    return (t.totalSpan.inMicroseconds ~/ frameInterval.inMicroseconds) + 1;
  }).fold<int>(0, (a, b) => a + b);
  return framesCount * refreshRate / costCount;
}
