import 'dart:async';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/models/chat_room_model.dart';
import 'package:peasmartcare/models/customer_info_model.dart';
import 'package:peasmartcare/models/electricity_location_customer_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/services/electricity_location_service.dart';
import 'package:peasmartcare/utils/app_util.dart';
import 'package:peasmartcare/utils/clear_count_notification_util.dart';
import 'package:peasmartcare/utils/firestore_log.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'select_electricity_location_list_event.dart';
part 'select_electricity_location_list_state.dart';

class SelectElectricityLocationListBloc extends Bloc<
    SelectElectricityLocationListEvent, SelectElectricityLocationListState> {
  ElectricityLocationImpService service = ElectricityLocationImpService();
  FirebaseMessaging firebaseMessaging = FirebaseMessaging();

  ResultData resultData;
  List<ElectricityLocationCustomerModel> customerList;

  SelectElectricityLocationListBloc()
      : super(SelectElectricityLocationListInitial());

  @override
  Stream<SelectElectricityLocationListState> mapEventToState(
      SelectElectricityLocationListEvent event) async* {
    try {
      if (event is SelectElectricityLocationListGetList) {
        yield SelectElectricityLocationListLoading();
        // print("aaa");

        resultData = await service.getList(
          idCard: ShareDataUtil.getIdCard(),
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        print("resultDataList = ${resultData.result} ");
        print("resultDataList = ${resultData.statusCode} ");
        print("resultDataList = ${resultData.statusMessage} ");

        yield SelectElectricityLocationListLoaded(
          result: resultData.result,
          electricityLocationCustomer: null,
          deleteSuccess: null,
        );
      } else if (event is SelectElectricityLocationListOnSelected) {
        print("bbb");

        yield SelectElectricityLocationListLoading();
        ResultData customerResulData = await service.getCustomerInfo(
          customerId: event.electricityLocationCustomer.customerId,
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        if (customerResulData.statusCode == 401) {
          yield SelectElectricityLocationListErrorUnauthorized();
        } else {
          if (customerResulData != null) {
            if (customerResulData.result is bool && !customerResulData.result) {
              yield SelectElectricityLocationListError(
                  message: "ไม่สามารถใช้งานรายการที่เลือกได้");
            } else {
              CustomerInfoModel customerInfo = customerResulData.result;
              UserModel user = ShareDataUtil.getUserInfo();

              await FirestoreLog.log(
                fullname: "${user.firstname} ${user.lastname}",
                authenKey: ShareDataUtil.getAuthenKey(),
                activity: "Select New CA",
                caNumber: customerInfo.caNumber,
              );

              firebaseMessaging.deleteInstanceID();
              ShareDataUtil.clearAllChatMasterId();

              //Clear noti
              await ClearCountNotificationUtil.news();
              await ClearCountNotificationUtil.activity();
              await ClearCountNotificationUtil.timeline();
              await ClearCountNotificationUtil.additionalService();
              await ClearCountNotificationUtil.reportIncident();
              //Group Chat
              await ClearCountNotificationUtil.chat(
                  AppData.groupChatChatMasterId);
              // firebaseMessaging.subscribeToTopic(AppData.groupChatChatMasterId);
              firebaseMessaging.subscribeToTopic(customerInfo.caNumber);
              ShareDataUtil.setAllChatMasterId(AppData.groupChatChatMasterId);

              //Single Chat
              ResultData chatResultData = await ChatImpService().getChatList(
                userId: ShareDataUtil.getUserId(),
                typeAccount: AppData.singleChatTypeAccount,
                customerId: customerInfo.customerId,
                authenKey: ShareDataUtil.getAuthenKey(),
              );

              if (chatResultData.statusCode == 401) {
                yield SelectElectricityLocationListErrorUnauthorized();
              } else {
                if (!AppUtil.isNil(chatResultData.result)) {
                  List<ChatRoomModel> chatRoomList = chatResultData.result;
                  chatRoomList.map((item) async {
                    if (!AppUtil.isNil(item.chatMasterId)) {
                      await ClearCountNotificationUtil.chat(item.chatMasterId);

                      // firebaseMessaging.subscribeToTopic(item.chatMasterId);
                      ShareDataUtil.setAllChatMasterId(item.chatMasterId);
                    }
                  }).toList();
                }

                ShareDataUtil.setCustomerInfo(customerInfo);
                ShareDataUtil.setLogin(true);

                yield SelectElectricityLocationListLoaded(
                  result: resultData.result,
                  electricityLocationCustomer:
                      event.electricityLocationCustomer,
                  deleteSuccess: null,
                );
              }
            }
          } else {
            yield SelectElectricityLocationListError(
                message: "ไม่สามารถใช้งานรายการที่เลือกได้");
          }
        }
      } else if (event is SelectElectricityLocationListOnDelete) {
        print("ccc");

        String customerId = event.customerId;
        String idCard = ShareDataUtil.getIdCard();
        String authenKey = ShareDataUtil.getAuthenKey();

        yield SelectElectricityLocationListLoading();
        ResultData deleteResult = await service.delete(
          customerId: customerId,
          idCard: idCard,
          authenKey: authenKey,
        );

        if (deleteResult.statusCode == 401) {
          yield SelectElectricityLocationListErrorUnauthorized();
        } else {
          yield SelectElectricityLocationListLoaded(
            result: resultData.result,
            electricityLocationCustomer: null,
            deleteSuccess: deleteResult.result,
          );
        }
      }
    } catch (e) {
      print("eee");

      yield SelectElectricityLocationListError(
          message: "ไม่สามารถใช้งานรายการที่เลือกได้");
    }
  }
}
