import 'package:chat/models/ChatMsg.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/msgHandler.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class MsgStateWidget extends StatefulWidget {
  final MsgModel msg;

  MsgStateWidget(this.msg);
  @override
  _MsgStateWidgetState createState() => _MsgStateWidgetState();
}

class _MsgStateWidgetState extends State<MsgStateWidget> {
  int sendState = MsgState.None;

  @override
  void initState() {
    super.initState();

    sendState = widget.msg.state;
    MessageMgr().on('Update Chat Message State', updateSendState);
  }

  @override
  void dispose() {
    MessageMgr().off('Update Chat Message State', updateSendState);
    super.dispose();
  }

  updateSendState(msg) {
    if (widget.msg.time == msg['time'] &&
        widget.msg.sessionId == msg['sessionId']) {
      widget.msg.state = msg['state'];
      if (mounted) {
        setState(() {
          sendState = widget.msg.state;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (sendState == MsgState.UploadFailed) {
      return Container(
        child: IconButton(
          iconSize: 22,
          icon: Icon(
            Icons.error_outline,
            color: Colors.red,
          ),
          onPressed: () {
            setState(() {
              sendState = MsgState.Uploading;
            });

            MessageMgr().emit('ReUpload Msg', widget.msg);
          },
        ),
      );
    }
    if (sendState == MsgState.SendingFailed) {
      return Container(
        child: IconButton(
          iconSize: 22,
          icon: Icon(
            Icons.error_outline,
            color: Colors.red,
          ),
          onPressed: () {
            print('重新发送');
            setState(() {
              sendState = MsgState.Sending;
            });
            MsgHandler.sendChatMsg(widget.msg);
          },
        ),
      );
    } else if (sendState == MsgState.SendingSuccess) {
      return Container(width: 0, height: 0);
    } else {
      return Align(
          alignment: Alignment.center,
          child: Padding(
              padding: EdgeInsets.only(top: 5),
              child: CupertinoActivityIndicator()));
    }
  }
}
