import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:intl/intl.dart';
import 'package:peasmartcare/models/chat_message_model.dart';
import 'package:peasmartcare/models/chat_notification_model.dart';
import 'package:peasmartcare/models/chat_user_model.dart';
import 'package:peasmartcare/models/customer_info_model.dart';
import 'package:peasmartcare/models/result_data_model.dart';
import 'package:peasmartcare/models/user_model.dart';
import 'package:peasmartcare/services/chat_service.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'chat_list_event.dart';
part 'chat_list_state.dart';

class ChatListBloc extends Bloc<ChatListEvent, ChatListState> {
  ChatImpService service = ChatImpService();
  FirebaseMessaging firebaseMessaging = FirebaseMessaging();
  int currentPage = 1;

  ResultData resultData;

  ChatListBloc() : super(ChatListInitial());

  subscribeChat({String topic}) {
    firebaseMessaging.subscribeToTopic(topic);
  }

  @override
  Stream<ChatListState> mapEventToState(ChatListEvent event) async* {
    try {
      if (event is ChatListGetList) {
        if (!event.isNewMessage && event.currentPage == 1) yield ChatListLoading();
        // yield ChatListLoading();
        // print(event.currentPage);
        // print(currentPage);

        //Group และ single ใช้อันเดียวกัน
        CustomerInfoModel customerInfo = await ShareDataUtil.getCustomerInfo();
        if (event.currentPage == 1) {
          currentPage = event.currentPage;
        }

        if (event.currentPage > currentPage) {
          ResultData resultDataTemp = await service.getGroupMessageList(
            userId: ShareDataUtil.getUserId(),
            typeChat: event.typeChat,
            typeAccount: event.typeAccount,
            chatMasterId: event.chatMasterId,
            authenKey: ShareDataUtil.getAuthenKey(),
            currentPage: event.currentPage,
            caNumber: customerInfo.caNumber,
            tsic: customerInfo.tsit,
            peaRegionId: customerInfo.peaRegionId,
            customerId: customerInfo.customerId,
          );

          currentPage = event.currentPage;

          // List<ChatMessageModel> reversedList = List.from(resultDataTemp.result.reversed);
          List<ChatMessageModel> reversedList = List.from(resultDataTemp.result);

          resultData.result.addAll(reversedList);
        } else {
          resultData = await service.getGroupMessageList(
            userId: ShareDataUtil.getUserId(),
            typeChat: event.typeChat,
            typeAccount: event.typeAccount,
            chatMasterId: event.chatMasterId,
            authenKey: ShareDataUtil.getAuthenKey(),
            currentPage: event.currentPage,
            caNumber: customerInfo.caNumber,
            tsic: customerInfo.tsit,
            peaRegionId: customerInfo.peaRegionId,
            customerId: customerInfo.customerId,
          );
        }

        // if (event.isGroupChat) {
        //   resultData = await service.getGroupMessageList(
        //     userId: ShareDataUtil.getUserId(),
        //     typeChat: event.typeChat,
        //     typeAccount: event.typeAccount,
        //     chatMasterId: event.chatMasterId,
        //     authenKey: ShareDataUtil.getAuthenKey(),
        //   );
        // } else {
        //   resultData = await service.getSingleMessageList(
        //     userId: ShareDataUtil.getUserId(),
        //     typeChat: event.typeChat,
        //     authenKey: ShareDataUtil.getAuthenKey(),
        //   );
        // }

        if (resultData.statusCode == 401) {
          yield ChatListErrorUnauthorized();
        } else {
          final List<ChatMessageModel> resultList = resultData.result;
          String currentDate = "";
          resultList.reversed.map((item) {
            List itemArr = item.createdAt.split(" ");
            if (itemArr[0] != currentDate) {
              item.currentDate = itemArr[0];
              currentDate = itemArr[0];
            } else {
              item.currentDate = "";
            }

            item.createdTime = "${itemArr[1]} น.";
          }).toList();
          yield ChatListLoaded(result: resultList, lastSend: DateTime.now());
        }
      } else if (event is ChatListOnSendMessage) {
        CustomerInfoModel customerInfo = await ShareDataUtil.getCustomerInfo();
        ResultData sendResult = await service.sendMessage(
          userId: ShareDataUtil.getUserId(),
          chatMasterId: event.chatMasterId,
          typeAccount: event.typeAccount,
          content: event.content,
          type: event.type,
          fileType: event.fileType,
          fullname: ShareDataUtil.getFullname(),
          authenKey: ShareDataUtil.getAuthenKey(),
          caNumber: customerInfo.caNumber,
          tsic: customerInfo.tsit,
          peaRegionId: customerInfo.peaRegionId,
          customerId: customerInfo.customerId,
          customerName: customerInfo.customerName,
          filename: event.fileName,
        );

        if (sendResult.result) {
          UserModel userInfo = ShareDataUtil.getUserInfo();

          ChatNotificationModel chatNoti = ChatNotificationModel();
          chatNoti.title = "${userInfo.firstname} ${userInfo.lastname}";

          if (event.type == 2) {
            chatNoti.body = "[รูปภาพ]";
          } else if (event.type == 3) {
            chatNoti.body = "ไฟล์";
          } else {
            chatNoti.body = event.content;
          }

          chatNoti.topic = event.chatMasterId;

          // final format = DateFormat('dd/MM/yyyy HH:mm');
          final format = NumberFormat("00", "en_US");

          DateTime now = DateTime.now();

          String content = event.content;
          int type = event.type;

          ChatMessageModel data = ChatMessageModel();
          data.content = content;
          data.fileName = event.fileName;
          data.type = type;
          data.isTempData = true;
          data.isReaded = false;
          // data.createdAt = format.format(now);
          data.createdAt = "${format.format(now.day)}/${format.format(now.month)}/${now.year + 543} ${format.format(now.hour)}:${format.format(now.minute)} น.";
          data.createdTime = "${format.format(now.hour)}:${format.format(now.minute)} น.";
          ChatUserModel user = ChatUserModel();
          user.id = userInfo.id;
          user.firstname = userInfo.firstname;
          user.lastname = userInfo.lastname;
          user.customerName = ShareDataUtil.getCustomerName();
          data.user = user;

          resultData.result.insert(0, data);

          if (resultData.statusCode == 401) {
            yield ChatListErrorUnauthorized();
          } else {
            yield ChatListLoaded(result: resultData.result, lastSend: DateTime.now());
          }

          List<String> registrationIdList = List<String>();
          // registrationIdList.add(ShareDataUtil.getFirebaseToken());

          chatNoti.registrationIds = registrationIdList;

          List<ChatNotificationDataParamModel> dataParamList = List<ChatNotificationDataParamModel>();

          ChatNotificationDataParamModel dataParam = ChatNotificationDataParamModel();
          dataParam.key = "click_action";
          dataParam.value = "FLUTTER_NOTIFICATION_CLICK";
          dataParamList.add(dataParam);

          dataParam = ChatNotificationDataParamModel();
          dataParam.key = "noti_type";
          dataParam.value = "CHAT";
          dataParamList.add(dataParam);

          dataParam = ChatNotificationDataParamModel();
          dataParam.key = "title";
          dataParam.value = "${userInfo.firstname} ${userInfo.lastname}";
          dataParamList.add(dataParam);

          dataParam = ChatNotificationDataParamModel();
          dataParam.key = "body";
          dataParam.value = event.type != 2 ? event.content : "[รูปภาพ]";
          dataParamList.add(dataParam);

          dataParam = ChatNotificationDataParamModel();
          dataParam.key = "isNewMessageChat";
          dataParam.value = "true";
          dataParamList.add(dataParam);

          dataParam = ChatNotificationDataParamModel();
          dataParam.key = "isGroupChat";
          dataParam.value = event.isGroupChat;
          dataParamList.add(dataParam);

          dataParam = ChatNotificationDataParamModel();
          dataParam.key = "typeChat";
          dataParam.value = event.typeChat;
          dataParamList.add(dataParam);

          dataParam = ChatNotificationDataParamModel();
          dataParam.key = "chatMasterId";
          dataParam.value = event.chatMasterId;
          dataParamList.add(dataParam);

          dataParam = ChatNotificationDataParamModel();
          dataParam.key = "chatTypeAccount";
          dataParam.value = event.typeAccount;
          dataParamList.add(dataParam);

          chatNoti.dataParams = dataParamList;

          await service.sendChatNoti(chatNoti: chatNoti);
        }
      } else if (event is ChatListClear) {
        resultData.result = null;
        yield ChatListInitial();
      }
    } catch (e) {
      yield ChatListError(message: "Error");
    }
  }
}
