import 'package:dart_ping/dart_ping.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../wallet/YSWalletRocChoose.dart';
import 'YSTools.dart';

class YSPingView extends StatefulWidget {
  final bool isEnable;
  final String? url;
  const YSPingView({Key? key, this.url, this.isEnable = true}) : super(key: key);

  @override
  YSPingViewState createState() => YSPingViewState();
}

class YSPingViewState extends State<YSPingView> {
  int _time = 0;
  @override
  void initState() {
    _getPingData();
    super.initState();
  }
  _getPingData() async{
    String url = widget.url??YSData().rpc;
    LogUtil.d(url);
    PingData data = await Ping(url, count: 1).stream.first;
    Duration? d = data.response?.time!;
    if(d!=null){
      _time = d.inMicroseconds;
    }
    setState(() {});
    LogUtil.d(data);

  }
  @override
  Widget build(BuildContext context) {
    Color color = _time<100?Colors.greenAccent:_time>100&&_time<200?Colors.orangeAccent:Colors.redAccent;
    return GestureDetector(
      onTap: (){
        if(widget.isEnable==false)return;
        Navigator.of(context).push(
            CupertinoPageRoute(builder: (context){
              return const YSWalletRocChoose();
            })
        );
      },
      behavior: HitTestBehavior.opaque,
      child: Row(
        children: [
          Container(
            margin: EdgeInsets.only(left: hsp(5)),
            height: hsp(20),
            width: hsp(20),
            alignment: Alignment.center,
            child: Container(
              height: hsp(5),
              width: hsp(5),
              decoration: BoxDecoration(
                  color: color,
                  borderRadius: const BorderRadius.all(Radius.circular(50))
              ),
            ),
          ),
          Text('$_time ms',style: TextStyle(fontSize: zsp(8),color: color),)
        ],
      ),
    );
  }
}