import 'dart:async';

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/result_data_model.dart';
import 'package:peasmartcare/services/chat_service.dart';
import 'package:peasmartcare/utils/app_util.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'chat_room_list_event.dart';
part 'chat_room_list_state.dart';

class ChatRoomListBloc extends Bloc<ChatRoomListEvent, ChatRoomListState> {
  ChatImpService service = ChatImpService();
  ResultData resultData;

  ChatRoomListBloc() : super(ChatRoomListInitial());

  @override
  Stream<ChatRoomListState> mapEventToState(ChatRoomListEvent event) async* {
    try {
      if (event is ChatRoomListGetList) {
        yield ChatRoomListLoading();
        resultData = await service.getChatList(
          userId: ShareDataUtil.getUserId(),
          typeAccount: event.isGroupChat ? AppData.groupChatTypeAccount : AppData.singleChatTypeAccount,
          customerId: ShareDataUtil.getCustomerId(),
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        if (!AppUtil.isNil(resultData?.result) && resultData.result.length > 0) {
          List<ChatRoomModel> resultList = List<ChatRoomModel>();
          resultList.add(resultData.result[0]);

          if (resultData.statusCode == 401) {
            yield ChatRoomListErrorUnauthorized();
          } else {
            yield ChatRoomListLoaded(result: resultList, deleteSuccess: null);
          }
        } else {
          yield ChatRoomListNotFound();
        }
      } else if (event is ChatRoomListOnDelete) {
        await Future.delayed(Duration(seconds: 2));
        if (resultData.statusCode == 401) {
          yield ChatRoomListErrorUnauthorized();
        } else {
          yield ChatRoomListLoaded(result: resultData.result, deleteSuccess: true);
        }
      }
    } catch (e) {
      yield ChatRoomListError(message: "Error");
    }
  }
}
