import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:ui';
import 'dart:typed_data';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:fluttericon/typicons_icons.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mime/mime.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:peasmartcare/blocs/chat_list/chat_list_bloc.dart';
import 'package:peasmartcare/components/chat/camera/camera.dart';
import 'package:peasmartcare/components/chat/chat_download_file.dart';
import 'package:peasmartcare/components/chat/chat_full_photo.dart';
import 'package:peasmartcare/constraints/api_path.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/models/chat_message_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/pages/chat_room/chat_reader_list.dart';
import 'package:peasmartcare/utils/app_util.dart';
import 'package:peasmartcare/utils/clear_count_notification_util.dart';
import 'package:peasmartcare/utils/extension_file_util.dart';
import 'package:peasmartcare/utils/share_data_util.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';

class Chat extends StatefulWidget {
  final String userId;
  final bool isGroupChat;
  final String typeChat;
  final String chatMasterId;
  final String typeAccount;

  const Chat({
    Key key,
    this.userId,
    this.isGroupChat,
    this.typeChat,
    this.chatMasterId,
    this.typeAccount,
  }) : super(key: key);

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

class _ChatState extends State<Chat> {
  final TextEditingController textEditingController = TextEditingController();
  ScrollController listScrollController;
  final FocusNode focusNode = FocusNode();
  final _appDataDir = Directory.systemTemp;
  static const _dataFilesBaseDirectoryName = "pea_files";
  ReceivePort _port = ReceivePort();
  String sendPort = "downloader_send_port";
  String currentDownloadFileName = "";

  List<ChatMessageModel> messageList = List<ChatMessageModel>();
  // ScrollController scrollController;
  File imageFile;
  bool sendMessageLoading = false;
  String imageBase64;
  String currentMessageDate = "";
  double _downloadProgress = 0;

  int totalPage = 1;
  int currentPage = 1;
  int currentAutoLoadMsg = 150;

  @override
  void initState() {
    _unbindBackgroundIsolate();
    _bindBackgroundIsolate();

    // context.read<ChatListBloc>().subscribeChat(topic: widget.chatMasterId);
    context.read<ChatListBloc>().subscribeChat(topic: ShareDataUtil.getCaNumber());
    context.read<ChatListBloc>().add(
          ChatListGetList(
            isGroupChat: widget.isGroupChat,
            typeChat: widget.typeChat,
            chatMasterId: widget.chatMasterId,
            typeAccount: widget.typeAccount,
            currentPage: currentPage,
          ),
        );
    // context.read<ChatCurrentMessageDateBloc>().add(ChatCurrentMessageDateGetData());
    listScrollController = ScrollController()..addListener(_scrollListener);
    super.initState();
  }

  @override
  void dispose() {
    _unbindBackgroundIsolate();
    listScrollController.removeListener(_scrollListener);
    super.dispose();
  }

  void _scrollListener() {
    // print("****************************");
    // print(listScrollController.position.extentBefore);
    // print("****************************");
    //currentAutoLoadMsg

    // print("****************************");
    // print("==> $currentPage : $totalPage");
    // print("==> ${listScrollController.position.extentBefore}");
    // print("==> ${listScrollController.position.extentAfter}");
    // print("****************************");

    // if (currentPage <= totalPage && listScrollController.position.extentBefore >= (currentPage * currentAutoLoadMsg)) {
    if (currentPage < totalPage && listScrollController.position.extentAfter == 0) {
      currentPage = currentPage + 1;

      context.read<ChatListBloc>().add(
            ChatListGetList(
              isGroupChat: widget.isGroupChat,
              typeChat: widget.typeChat,
              chatMasterId: widget.chatMasterId,
              typeAccount: widget.typeAccount,
              currentPage: currentPage,
            ),
          );
      // setState(() {
      //   items.addAll(new List.generate(42, (index) => 'Inserted $index'));
      // });
    }
    //  else if (currentPage < totalPage && listScrollController.position.extentBefore == 0) {
    //   currentPage = 1;
    // }
  }

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;

    // final progressModal = ProgressHUD.of(context);

    return WillPopScope(
      child: ProgressHUD(
        child: Builder(
          builder: (context) {
            final progressModal = ProgressHUD.of(context);

            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (_downloadProgress == 100) {
                progressModal.dismiss();
                setState(() {
                  _downloadProgress = 0.0;
                });

                _alertDownloaded();
              }
            });
            return Container(
              color: Colors.purple[50],
              child: Stack(
                children: <Widget>[
                  Column(
                    children: <Widget>[
                      // List of messages
                      buildListMessage(progressModal),

                      // Sticker
                      // (isShowSticker ? buildSticker() : Container()),
                      buildSendMessageLoading(),

                      // Input content
                      buildInput(),
                    ],
                  ),
                ],
              ),
            );
          },
        ),
      ),
      onWillPop: onBackPress,
    );
  }

  Widget buildListMessage(progressModal) {
    return Flexible(
      child: Center(
        child: BlocListener<ChatListBloc, ChatListState>(
          listener: (context, state) {
            if (state is ChatListLoaded) {
              setState(() {
                sendMessageLoading = false;
              });
            } else if (state is ChatListErrorUnauthorized) {
              Navigator.of(context).popUntil((route) => route.isFirst);
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(builder: (context) => LogoutPage()),
              );
            }
          },
          child: BlocBuilder<ChatListBloc, ChatListState>(
            builder: (context, state) {
              if (state is ChatListLoading) {
                return Loading();
              } else if (state is ChatListLoaded) {
                messageList = state.result;

                return ListView.builder(
                  padding: EdgeInsets.all(10.0),
                  itemBuilder: (context, index) => buildItem(index, messageList[index], messageList, progressModal),
                  itemCount: !AppUtil.isNil(messageList?.length) ? messageList.length : 0,
                  reverse: true,
                  controller: listScrollController,
                );
              }

              return EmptyBox();
            },
          ),
        ),
      ),
    );
  }

  Widget buildSendMessageLoading() {
    return sendMessageLoading
        ? Row(
            children: <Widget>[
              Container(
                padding: EdgeInsets.all(15),
                child: Loading(height: 15),
              ),
            ],
            mainAxisAlignment: MainAxisAlignment.end,
          )
        : EmptyBox(heightFactor: 0);
  }

  Widget buildItem(int index, ChatMessageModel item, List<ChatMessageModel> allItem, progressModal) {
    // _getMessageDate(item.createdAt, allItem, index);

    if (!AppUtil.isNil(allItem?.length) && allItem.length > 0) {
      totalPage = allItem[0].totalPage;
    }

    return Column(
      children: [
        if (!AppUtil.isNil(item.currentDate))
          Container(
            child: Text(
              item.currentDate ?? "",
              style: TextStyle(color: Color(AppData.whiteColor)),
            ),
            // constraints: BoxConstraints(maxWidth: deviceSize.width / 1.5),
            padding: EdgeInsets.fromLTRB(15.0, 5, 15.0, 5),
            decoration: BoxDecoration(color: Colors.grey, borderRadius: BorderRadius.circular(15)),
            margin: EdgeInsets.symmetric(vertical: 15),
            // margin: EdgeInsets.only(bottom: isLastMessageRight(index) ? 20.0 : 10.0, right: 10.0),
          ),
        widget.userId.contains(item.user.id) ? buildSender(index, item, progressModal) : buildReceiver(index, item, progressModal),
      ],
    );
  }

  void _getMessageDate(item, List<ChatMessageModel> allItem, index) {
    List itemArr = item.split(" ");

    if (!AppUtil.isNil(itemArr?.length) && itemArr.length > 0) {
      // print("==========");
      // print(currentMessageDate);
      // print(itemArr[0]);
      // print("==========");
      // if (!currentMessageDate.contains(itemArr[0])) {
      //   print("=-------------");

      //   Future.delayed(
      //       Duration(seconds: 0),
      //       () => setState(() {
      //             currentMessageDate = itemArr[0];
      //           }));
      // } else {
      //   currentMessageDate = "cc";
      // }

      // context.read<ChatCurrentMessageDateBloc>().add(ChatCurrentMessageDateAddCurrentDate(
      //       currentDate: itemArr[0],
      //     ));
    }
  }

  Widget buildSender(int index, ChatMessageModel item, progressModal) {
    Size deviceSize = MediaQuery.of(context).size;
    dynamic contentWidget = EmptyBox(heightFactor: 0);
    if (item.type == 1) {
      contentWidget = InkWell(
        child: Container(
          child: Text(
            item.content,
            style: TextStyle(color: Color(AppData.whiteColor)),
          ),
          constraints: BoxConstraints(maxWidth: deviceSize.width / 1.5),
          padding: EdgeInsets.fromLTRB(15.0, 10.0, 15.0, 10.0),
          decoration: BoxDecoration(color: Color(AppData.greyColor), borderRadius: BorderRadius.circular(15)),
          margin: EdgeInsets.only(bottom: 10.0, right: 5),
        ),
        onTap: () {
          showCupertinoModalBottomSheet(
            expand: false,
            context: context,
            backgroundColor: Colors.transparent,
            builder: (context, scrollController) => ChatReaderList(
              scrollController: scrollController,
              id: item.id,
            ),
          );
        },
      );
    } else if (item.type == 2) {
      Widget imageChild;
      if (item.isTempData != null && item.isTempData) {
        Uint8List bytes = base64.decode(item.content);
        imageChild = Image.memory(
          bytes,
          width: 150,
          fit: BoxFit.fitWidth,
        );
      } else {
        try {
          imageChild = CachedNetworkImage(
            width: 150,
            imageUrl: "${APIPath.chatDownloadFile}?Id=${item.id}&AuthenKey=${ShareDataUtil.getAuthenKey()}",
            progressIndicatorBuilder: (context, url, downloadProgress) => Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  padding: EdgeInsets.all(5),
                  width: 25,
                  height: 25,
                  child: CircularProgressIndicator(
                    value: downloadProgress.progress,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[400]),
                  ),
                ),
              ],
            ),
            errorWidget: (context, url, error) => Icon(Icons.error),
            fit: BoxFit.fitWidth,
          );
        } catch (e) {
          imageChild = Icon(Icons.error);
        }
      }

      contentWidget = InkWell(
        child: Container(
          child: ClipRRect(
            child: imageChild,
            borderRadius: BorderRadius.circular(15),
          ),
          margin: EdgeInsets.only(bottom: 10.0, right: 5),
          constraints: BoxConstraints(maxWidth: 250),
        ),
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => ChatFullPhoto(
                      chatId: item.id,
                      imageContent: item.content,
                      isTempData: item.isTempData,
                    )),
          );
        },
      );
    } else if (item.type == 3) {
      contentWidget = ChatDownloadFile(
        chatMessage: item,
        onTap: () async {
          bool existsFile = await _existsFile(item);
          if (existsFile) {
            _alertDownloaded();
          } else {
            _onDownloadFile(item, progressModal);
          }
        },
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        if (!AppUtil.isNil(item?.user?.customerName))
          Container(
            child: Text(
              "${item?.user?.customerName ?? ''}",
              style: TextStyle(color: Colors.grey),
            ),
            padding: EdgeInsets.only(right: 5),
          ),
        Container(
          child: Text(
            "${item.user.firstname} ${item.user.lastname}",
            style: TextStyle(color: Colors.grey),
          ),
          padding: EdgeInsets.only(right: 5),
        ),
        // Container(
        //   child: Text(
        //     "${item.createdAt}",
        //     style: TextStyle(color: Colors.grey),
        //   ),
        //   padding: EdgeInsets.only(right: 5),
        // ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (item.isReaded)
                  InkWell(
                    child: Padding(
                      padding: const EdgeInsets.only(right: 5),
                      child: Text(
                        "อ่านแล้ว",
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: 12,
                        ),
                      ),
                    ),
                    onTap: () {
                      showCupertinoModalBottomSheet(
                        expand: false,
                        context: context,
                        backgroundColor: Colors.transparent,
                        builder: (context, scrollController) => ChatReaderList(
                          scrollController: scrollController,
                          id: item.id,
                        ),
                      );
                    },
                  ),
                Container(
                  child: Text(
                    "${item.createdTime}",
                    style: TextStyle(
                      color: Colors.grey,
                      fontSize: 12,
                    ),
                  ),
                  padding: EdgeInsets.only(right: 5),
                ),
              ],
            ),
            contentWidget,
          ],
        ),
      ],
    );
  }

  Widget buildReceiver(int index, ChatMessageModel item, progressModal) {
    Size deviceSize = MediaQuery.of(context).size;
    dynamic contentWidget = EmptyBox(heightFactor: 0);

    if (item.type == 1) {
      contentWidget = Container(
        child: Text(
          item.content,
          style: TextStyle(color: Color(AppData.whiteColor)),
        ),
        constraints: BoxConstraints(maxWidth: deviceSize.width / 1.5),
        padding: EdgeInsets.fromLTRB(15.0, 10.0, 15.0, 10.0),
        decoration: BoxDecoration(color: Color(AppData.greyColor), borderRadius: BorderRadius.circular(15)),
        margin: EdgeInsets.only(bottom: 10.0, right: 10.0),
        // margin: EdgeInsets.only(bottom: isLastMessageRight(index) ? 20.0 : 10.0, right: 10.0),
      );
    } else if (item.type == 2) {
      Widget imageChild;
      if (item.isTempData != null && item.isTempData) {
        Uint8List bytes = base64.decode(item.content);
        imageChild = Image.memory(
          bytes,
          width: 150,
          fit: BoxFit.fitWidth,
        );
      } else {
        try {
          imageChild = Container(
            width: 150,
            child: CachedNetworkImage(
              imageUrl: "${APIPath.chatDownloadFile}?Id=${item.id}&AuthenKey=${ShareDataUtil.getAuthenKey()}",
              progressIndicatorBuilder: (context, url, downloadProgress) => Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    padding: EdgeInsets.all(5),
                    width: 25,
                    height: 25,
                    child: CircularProgressIndicator(
                      value: downloadProgress.progress,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[400]),
                    ),
                  ),
                ],
              ),
              errorWidget: (context, url, error) => Icon(Icons.error),
              fit: BoxFit.fitWidth,
            ),
          );
        } catch (e) {
          imageChild = Icon(Icons.error);
        }
      }
      contentWidget = InkWell(
        child: Container(
          child: ClipRRect(
            child: imageChild,
            borderRadius: BorderRadius.circular(15),
          ),
          margin: EdgeInsets.only(bottom: 10.0, right: 5),
          constraints: BoxConstraints(maxWidth: 250),
        ),
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => ChatFullPhoto(
                      chatId: item.id,
                      imageContent: item.content,
                      isTempData: item.isTempData,
                    )),
          );
        },
      );
    } else if (item.type == 3) {
      contentWidget = ChatDownloadFile(
        chatMessage: item,
        onTap: () async {
          bool existsFile = await _existsFile(item);
          if (existsFile) {
            _alertDownloaded();
          } else {
            _onDownloadFile(item, progressModal);
          }
        },
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (!AppUtil.isNil(item?.user?.customerName))
          Container(
            child: Text(
              "${item?.user?.customerName ?? ''}",
              style: TextStyle(color: Colors.grey),
            ),
            padding: EdgeInsets.only(left: 5),
          ),
        Container(
          child: Text(
            "${item.user.firstname} ${item.user.lastname}",
            style: TextStyle(color: Colors.grey),
          ),
          padding: EdgeInsets.only(left: 5),
        ),
        // Container(
        //   child: Text(
        //     "${item.createdAt}",
        //     style: TextStyle(color: Colors.grey),
        //   ),
        //   padding: EdgeInsets.only(left: 5),
        // ),
        Row(
          // mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            contentWidget,
            Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  child: Text(
                    "${item.createdTime}",
                    style: TextStyle(
                      color: Colors.grey,
                      fontSize: 12,
                    ),
                  ),
                  // padding: EdgeInsets.only(left: 5),
                ),
              ],
            ),
          ],
        ),
      ],
    );
  }

  Future<String> _createFileFromString(String encodedStr) async {
    Uint8List bytes = base64.decode(encodedStr);

    // String mimeType = "application/zip"; //lookupMimeType('file', headerBytes: bytes);
    String mimeType = lookupMimeType('file', headerBytes: bytes);

    String dir = (await getApplicationDocumentsDirectory()).path;

    File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ".${ExtensionFileUtil.fromMimeType(mimeType)}");
    await file.writeAsBytes(bytes);
    return file.path;
  }

  Widget buildInput() {
    return Container(
      child: Row(
        children: <Widget>[
          //Attach File
          Material(
            child: Container(
              child: IconButton(
                icon: Icon(Typicons.attach),
                onPressed: getFile,
                color: Color(AppData.purpleColor),
              ),
            ),
            color: Colors.purple[50],
          ),

          //Take Photo
          Material(
            child: Container(
              child: IconButton(
                icon: Icon(Typicons.camera_outline),
                onPressed: takePhoto,
                color: Color(AppData.purpleColor),
              ),
            ),
            color: Colors.purple[50],
          ),

          // Button send image
          Material(
            child: Container(
              child: IconButton(
                icon: Icon(Typicons.picture_outline),
                onPressed: getImage,
                color: Color(AppData.purpleColor),
              ),
            ),
            color: Colors.purple[50],
          ),

          // Material(
          //   child: Container(
          //     margin: EdgeInsets.symmetric(horizontal: 1.0),
          //     child: IconButton(
          //       icon: Icon(Icons.face),
          //       onPressed: getSticker,
          //       color: Color(AppData.purpleColor),
          //     ),
          //   ),
          //   color: Colors.purple[50],
          // ),

          // Edit text
          Flexible(
            child: Container(
              child: TextField(
                onSubmitted: (value) {
                  onSendMessage(
                    content: textEditingController.text,
                    type: 1,
                    chatMasterId: widget.chatMasterId,
                    typeAccount: widget.typeAccount,
                    typeChat: widget.typeChat,
                    isGroupChat: widget.isGroupChat,
                  );
                },
                style: TextStyle(
                  color: Color(AppData.purpleColor),
                  fontSize: 15.0,
                ),
                controller: textEditingController,
                decoration: InputDecoration.collapsed(
                  hintText: 'พิมพ์ข้อความ...',
                  hintStyle: TextStyle(
                    color: Color(AppData.greyColor),
                  ),
                ),
                focusNode: focusNode,
              ),
            ),
          ),

          // Button send message
          Material(
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 8.0),
              child: IconButton(
                icon: Icon(Icons.send),
                onPressed: () => onSendMessage(
                  content: textEditingController.text,
                  type: 1,
                  chatMasterId: widget.chatMasterId,
                  typeAccount: widget.typeAccount,
                  typeChat: widget.typeChat,
                  isGroupChat: widget.isGroupChat,
                ),
                color: Color(AppData.purpleColor),
              ),
            ),
            color: Colors.purple[50],
          ),
        ],
      ),
      width: double.infinity,
      height: 50.0,
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(color: Color(AppData.greyColor), width: 0.5),
        ),
        color: Colors.purple[50],
      ),
    );
  }

  void onSendMessage({
    String content,
    int type,
    String chatMasterId,
    String typeAccount,
    String typeChat,
    bool isGroupChat,
    String fileType,
    String fileName,
  }) {
    if (!AppUtil.isNil(content)) {
      setState(() {
        sendMessageLoading = true;
      });

      context.read<ChatListBloc>().add(
            ChatListOnSendMessage(
              chatMasterId: chatMasterId,
              typeAccount: typeAccount,
              content: content,
              type: type,
              typeChat: typeChat,
              isGroupChat: isGroupChat,
              fileType: fileType,
              fileName: fileName,
            ),
          );
      textEditingController.text = "";
    }
  }

  Future getImage() async {
    ImagePicker imagePicker = ImagePicker();
    PickedFile pickedFile;

    pickedFile = await imagePicker.getImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      imageFile = File(pickedFile.path);

      List<int> fileBytes = imageFile.readAsBytesSync();
      String base64File = base64Encode(fileBytes);

      if (imageFile != null) {
        setState(() {
          sendMessageLoading = true;
        });

        onSendMessage(
          content: base64File,
          type: 2,
          chatMasterId: widget.chatMasterId,
          typeAccount: widget.typeAccount,
          typeChat: widget.typeChat,
          isGroupChat: widget.isGroupChat,
        );

        Future.delayed(Duration(seconds: 3), () {
          setState(() {
            sendMessageLoading = false;
          });
        });
      }
    }
  }

  Future getFile() async {
    List<String> allowedExtensionList = [
      'jpg',
      'jpeg',
      'png',
      'pdf',
      'doc',
      'docx',
      'ppt',
      'pptx',
      'xls',
      'xlsx',
      'txt',
      'zip',
      'rar',
      'odt',
      'rtf',
      'odp',
      'ods',
      'mp4',
      'mov',
      'mpeg',
      'avi',
      '3gp',
      'mkv',
      'wav',
      'mp3',
      'tiff',
      'tif',
      'gif',
      'bmp',
      'xml',
      'csv',
    ];
    FilePickerResult fileResult = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: allowedExtensionList,
    );

    if (fileResult != null) {
      PlatformFile platformFile = fileResult.files.first;

      List<String> searchFile = allowedExtensionList.where((item) => item.toLowerCase().contains(platformFile.extension.toLowerCase())).toList();

      if (!AppUtil.isNil(searchFile) && searchFile.length > 0) {
        File file = File(platformFile.path);

        // print(platformFile.name);

        // File zipFile;
        // try {
        //   zipFile = await _zipFiles(platformFile);
        // } catch (e) {
        //   print(e);
        // }

        List<int> fileBytes = file.readAsBytesSync();
        // List<int> fileBytes = zipFile.readAsBytesSync();
        String base64File = base64Encode(fileBytes);

        setState(() {
          sendMessageLoading = true;
        });

        onSendMessage(
          content: base64File,
          type: 3,
          chatMasterId: widget.chatMasterId,
          typeAccount: widget.typeAccount,
          typeChat: widget.typeChat,
          isGroupChat: widget.isGroupChat,
          fileType: platformFile.extension,
          fileName: platformFile.name,
        );

        Future.delayed(Duration(seconds: 3), () {
          setState(() {
            sendMessageLoading = false;
          });
        });
      } else {
        SweetAlert.show(
          context,
          subtitle: "ไม่สนับสนุนรูปแบบไฟล์ ${platformFile.extension}",
          style: SweetAlertStyle.error,
        );
      }
    }
  }

  Future takePhoto() async {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CameraScreen(
          chatMasterId: widget.chatMasterId,
          typeAccount: widget.typeAccount,
          typeChat: widget.typeChat,
          isGroupChat: widget.isGroupChat,
        ),
      ),
    );
  }

  void getSticker() {
    // Hide keyboard when sticker appear
    // focusNode.unfocus();
    // setState(() {
    //   isShowSticker = !isShowSticker;
    // });

    print("getSticker");
  }

  Widget _showDownloadFile() {}

  void _bindBackgroundIsolate() {
    bool isSuccess = IsolateNameServer.registerPortWithName(_port.sendPort, sendPort);
    // print("#######");
    // print(isSuccess);
    // print("#######");
    if (!isSuccess) {
      _unbindBackgroundIsolate();
      _bindBackgroundIsolate();
      return;
    }
    _port.listen((dynamic data) async {
      String id = data[0];
      DownloadTaskStatus status = data[1];
      double progress = data[2] * 1.0;

      // print("-------");
      // print(progress);
      // print("-------");

      setState(() {
        _downloadProgress = progress;
      });
    });
  }

  void _unbindBackgroundIsolate() {
    IsolateNameServer.removePortNameMapping(sendPort);
  }

  bool _checkImageLink(String url) {
    // Future<bool> result = () async {
    //   final response = await Dio().get(url);
    //   if (response.statusCode == 200) {
    //     return Future<true>;
    //   }

    //   return false;
    // };

    return false;
  }

  Future<bool> onBackPress() {
    print("onBackPress");
    // if (isShowSticker) {
    //   setState(() {
    //     isShowSticker = false;
    //   });
    // } else {
    //   FirebaseFirestore.instance
    //       .collection('users')
    //       .doc(id)
    //       .update({'chattingWith': null});
    //   Navigator.pop(context);
    // }

    context.read<ChatListBloc>().add(ChatListClear());
    ClearCountNotificationUtil.chat(widget.chatMasterId);
    Navigator.pop(context);
    return Future.value(false);
  }

  Future<void> openFile() async {
    print("openFile");
    String localPath = (await AppUtil.getLocalPath()) + Platform.pathSeparator + 'pea_files';

    final result = await OpenFile.open("$localPath/$currentDownloadFileName");
  }

  _existsFile(ChatMessageModel item) async {
    setState(() {
      currentDownloadFileName = item.fileName;
    });
    String localPath = (await AppUtil.getLocalPath()) + Platform.pathSeparator + 'pea_files';
    bool existsFile = await File("$localPath/$currentDownloadFileName").exists();

    return existsFile;
  }

  _alertDownloaded() {
    return SweetAlert.show(
      context,
      subtitle: "ดาวน์โหลดไฟล์สำเร็จ",
      style: SweetAlertStyle.success,
      showCancelButton: true,
      cancelButtonText: "ปิด",
      confirmButtonText: "เปิดไฟล์",
      onPress: (bool isConfirm) {
        if (isConfirm) {
          openFile();
        }

        return true;
      },
    );
  }

  _onDownloadFile(ChatMessageModel item, progressModal) async {
    String localPath = (await AppUtil.getLocalPath()) + Platform.pathSeparator + 'pea_files';

    final savedDir = Directory(localPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }

    progressModal.showWithText('กำลังดาวน์โหลด...');

    String downloader = await FlutterDownloader.enqueue(
      // url: item.fileUrl,
      url: "${APIPath.chatDownloadFile}?Id=${item.id}&AuthenKey=${ShareDataUtil.getAuthenKey()}",
      fileName: currentDownloadFileName,
      savedDir: localPath,
      showNotification: true, // show download progress in status bar (for Android)
      openFileFromNotification: true, // click on notification to open downloaded file (for Android)
    );
  }
}
