import 'dart:convert';
import 'dart:io';
import 'dart:math';

Stream<double> getCpuUsagePercentage() async* {
  while (true) {
    if (Platform.isLinux) {
      await Future.delayed(const Duration(milliseconds: 100));
      final vmstat = await Process.start(
        'vmstat',
        [
          '1',
          '2',
        ],
      );
      final tail = await Process.start('tail', ['-1']);
      final awk = await Process.start('awk', ['{print \$15}']);

      vmstat.stdout.pipe(tail.stdin);
      tail.stdout.pipe(awk.stdin);

      var cpuUsage = await awk.stdout.transform(utf8.decoder).join();

      yield 100 - double.parse(cpuUsage);
    } else {
      await Future.delayed(const Duration(milliseconds: 100));
      yield Random().nextDouble() * 100;
    }
  }
}
