import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:universal_html/js.dart' as js;

class MemoryMonitor extends StatefulWidget {
  const MemoryMonitor({super.key});

  @override
  State<MemoryMonitor> createState() => _MemoryMonitorState();
}

class _MemoryMonitorState extends State<MemoryMonitor> {
  String totalMemory = '';
  String allocatedMemory = '';
  String availableMemory = '';
  Timer? _timer;

  @override
  Widget build(BuildContext context) {
    if (totalMemory.isEmpty) {
      return Container();
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Flexible(
          child: Text(
            '已用内存：$totalMemory MB',
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: LabColors.text300),
          ),
        ),
        Flexible(child: SizedBox(width: 10)),
        Flexible(
          child: Text(
            '可用内存：$availableMemory MB',
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: LabColors.text300),
          ),
        ),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(
      const Duration(seconds: 3),
      (Timer timer) {
        updateMemoryInfo();
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
    _timer = null;
  }

  void updateMemoryInfo() {
    try {
      // 更新内存数据
      js.context.callMethod("getMemoryUsageInfo", [
        (
          dynamic success,
          dynamic totalMemory,
          dynamic allocatedMemory,
          dynamic availableMemory,
        ) {
          if (success is bool && success) {
            if (totalMemory is num &&
                allocatedMemory is num &&
                availableMemory is num) {
              final String _totalMemory =
                  (totalMemory.toInt() / 1048576).toStringAsFixed(2);
              final String _allocatedMemory =
                  (allocatedMemory.toInt() / 1048576).toStringAsFixed(2);
              final String _availableMemory =
                  (availableMemory.toInt() / 1048576).toStringAsFixed(2);
              setState(() {
                this.totalMemory = _totalMemory;
                this.allocatedMemory = _allocatedMemory;
                this.availableMemory = _availableMemory;
              });
            } else {
              print('内存数据类型错误');
            }
          } else {
            print('获取内存数据失败');
          }
        }
      ]);
    } catch (e) {
      print('获取内存数据失败');
    }
  }
}
