Untitled

 avatar
user_8529798
plain_text
a month ago
73 kB
3
Indexable
import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:Buildeffective/app_constants.dart';
import 'package:Buildeffective/src/app_notification.dart';
import 'package:Buildeffective/src/model/current_user_details.dart';
import 'package:Buildeffective/src/model/dashboard_property_list_response.dart';
import 'package:Buildeffective/src/model/notification_payload.dart';
import 'package:Buildeffective/src/model/signin_response.dart';
import 'package:Buildeffective/src/model/space_zone_list_model.dart';
import 'package:Buildeffective/src/model/spaces_response.dart';
import 'package:Buildeffective/src/model/upload_file_notification_model.dart';
import 'package:Buildeffective/src/repository/auth_repository.dart';
import 'package:Buildeffective/src/repository/create_property_repository.dart';
import 'package:Buildeffective/src/repository/product_repository.dart';
import 'package:Buildeffective/src/repository/space_repository.dart';
import 'package:Buildeffective/src/screens/claim_property_flow/claim_property_screen.dart';
import 'package:Buildeffective/src/screens/onboard_flow/reset_password_screen.dart';
import 'package:Buildeffective/src/screens/product_aggregation_screen/product_aggregation_models/product_list_finish_heading_model.dart';
import 'package:Buildeffective/src/screens/product_aggregation_screen/product_aggregation_screens/product_aggregation_list_screen.dart';
import 'package:Buildeffective/src/screens/product_screen/product_models/product_holdings_model.dart';
import 'package:Buildeffective/src/screens/signin_screen/signin_screen.dart';
import 'package:Buildeffective/src/screens/space_feature_summary_new/spaces_summary_screen_new.dart';
import 'package:Buildeffective/src/utils/comman_export.dart';
import 'package:Buildeffective/src/utils/static_classes.dart';
import 'package:Buildeffective/src/utils/user_verified_view.dart';
import 'package:Buildeffective/src/whatsapp_image_picker/configs/image_picker_configs.dart';
import 'package:Buildeffective/src/whatsapp_image_picker/models/image_object.dart';
import 'package:Buildeffective/src/whatsapp_image_picker/picker/image_picker.dart';
import 'package:dio/dio.dart';
import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get_it/get_it.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:mobx/mobx.dart';
import 'package:navigation_history_observer/navigation_history_observer.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';

import '../config.dart';
import 'app.dart';
import 'networks/api_client.dart';
import 'screens/dashboard/dashboard_screen.dart';
import 'screens/new_create_account_flow/join_existing_account_flow/member_request_pending_screen.dart';
import 'screens/onboard_flow/store/signup_onboard_viewmodel.dart';

class AppHelper {
  //making singleton class...
  static final AppHelper _singleton = AppHelper._internal();

  factory AppHelper() {
    return _singleton;
  }

  AppHelper._internal();

  //navigation history observer to observe page changes ans stack
  final NavigationHistoryObserver historyObserver = NavigationHistoryObserver();
  int historyCount = 0;
  int poppedCount = 0;

  //dynamic links...
  FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;

  //checking current channel for notification patch on

  //Get Edit Group Update LocatableId
  static Map<String, dynamic>? locatableIdAndName;

  static StreamController controller = StreamController<Map<String, dynamic>>.broadcast();

  ApiState getSpaceListZoneApiState = ApiState.init;
  ApiState getSpaceListDataApiState = ApiState.init;
  SpaceZoneListModel? spaceZoneListModel;
  String? selectedSpaceZoneId = "Interior".toLowerCase();
  ObservableList<UnitSpacesFloorWise> spaceInteriorInfoList = ObservableList();
  ProductHoldings? productHoldings;
  ObservableList<UnitSpace> getProductAggregationSpaceList = ObservableList();
  ApiState showProductAggregationApiState = ApiState.init;
  ObservableList<ProductListFinishHeading> showProductListFinishesList = ObservableList();

  removeNotificationById(int id) {
    flutterLocalNotificationsPlugin.cancel(id);
  }

  removeNotification() {
    flutterLocalNotificationsPlugin.cancelAll();
  }

  increaseNotificationId() {
    App.NOTIFICATION_ID++;
  }

  NotificationPayload createDocUploadPayload({required int notificationId}) {
    UploadFileNotificationModel model = App.uploadNotifications.firstWhere((element) => element.id == notificationId);
    var ref1 = model.totalCount > 1 ? 'documents are' : 'document is';
    var ref2 = model.errorCount > 1 ? 'documents are' : 'document is';
    NotificationPayload notificationPayload = new NotificationPayload()
      ..channelTitle = model.title
      ..message = model.errorCount == 0 ? '${model.uploadedCount}/${model.totalCount} $ref1 uploaded.' : '${model.uploadedCount}/${model.totalCount} $ref1 uploaded and ${model.errorCount} $ref2 already present.';

    return notificationPayload;
  }

  NotificationPayload createPhotoUploadPayload({required int notificationId}) {
    UploadFileNotificationModel model = App.uploadNotifications.firstWhere((element) => element.id == notificationId);
    var ref1 = model.totalCount > 1 ? 'images are' : 'image is';
    var ref2 = model.errorCount > 1 ? 'images are' : 'image is';
    NotificationPayload notificationPayload = new NotificationPayload()
      ..channelTitle = model.title
      ..message = model.errorCount == 0 ? '${model.uploadedCount}/${model.totalCount} $ref1 uploaded.' : '${model.uploadedCount}/${model.totalCount} $ref1 uploaded and ${model.errorCount} $ref2 already present.';

    return notificationPayload;
  }

  void showNoClickableNotification(int id, NotificationPayload payload) async {
    final initializationSettings = InitializationSettings(
      android: AppNotification.initializationSettingsAndroid,
      iOS: AppNotification.initializationSettingsIOS,
    );

    //local notification initializing..
    await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onDidReceiveNotificationResponse: AppNotification.onDidReceiveNotificationResponse,
      onDidReceiveBackgroundNotificationResponse: AppNotification.onDidReceiveNotificationResponse,
    );

    //showing notification
    await flutterLocalNotificationsPlugin.show(id, payload.channelTitle, payload.message, AppNotification.notificationDetails);
  }

  void registerFirebaseTokenToBackend() async {
    await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(AppNotification.channel);

    //getting token for the first time..
    FirebaseMessaging.instance.getToken().then((token) async {
      print("Firebase Token init : -- $token");

      final preferences = GetIt.instance<Preferences>();
      preferences.setFirebaseToken(token!);
      String? userToken = await preferences.getUserToken();
      if (!userToken.isNullOrEmpty()) {
        App.client.addDevice(token, PushProvider.firebase, pushProviderName: STREAM_CHAT_CERTIFICATE);
      }
    });

    //listening for the token updates here..
    FirebaseMessaging.instance.onTokenRefresh.listen((token) async {
      print("Firebase Token Updated : -- $token");

      final preferences = GetIt.instance<Preferences>();
      preferences.setFirebaseToken(token);
      String? userToken = await preferences.getUserToken();
      if (!userToken.isNullOrEmpty()) {
        App.client.addDevice(token, PushProvider.firebase, pushProviderName: STREAM_CHAT_CERTIFICATE);
      }
    });
  }

  void onBackgroundMessageReceiveViaStreamChat(Event event) async {
    final currentUserId = App.client.state.currentUser!.id;
    if (event.user == null) return;
    if (![
          EventType.messageNew,
          EventType.notificationMessageNew,
        ].contains(event.type) ||
        event.user!.id == currentUserId) {
      return;
    }
    if (event.message == null) return;
    // if(event.message?.user?.id == )
    print("showing notification from the app.dart");
    String propertyId = (event.channel!.extraData['tags'] as List).first['propertyId'].toString();
    String propertyName = (event.channel!.extraData['tags'] as List).first['propertyName'].toString();
    final preference = GetIt.instance<Preferences>();
    final notificationStyle = await preference.getNotificationStyle();

    NotificationPayload notificationPayload = new NotificationPayload()
      ..channelTitle = AppHelper().setTitleOfNotification(type: notificationStyle!, propertyName: propertyName, event: event)
      ..message = AppHelper().setBodyOfNotification(type: notificationStyle, propertyName: propertyName, event: event)
      ..propertySlug = propertyId
      ..messageId = event.message!.id
      ..channelType = event.channel!.type
      ..channelId = event.channel!.id;

    log("onBackgroundMessageReceiveViaStreamChat" + " ======> " + "${notificationPayload.messageId}");
  }

  ThemeData getApplicationTheme() {
    return ThemeData(
      appBarTheme: AppBarTheme(
        color: BEColors.white,
        elevation: 0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            bottomLeft: Radius.circular(10),
            bottomRight: Radius.circular(10),
          ),
        ),
        titleSpacing: 0,
        shadowColor: Color.fromRGBO(73, 73, 73, 0.1),
        titleTextStyle: BETextStyles.H6StyleWithDarkBlueColor,
        iconTheme: IconThemeData(color: BEColors.darkBlue, size: 24, applyTextScaling: true),
      ),
      useMaterial3: false,
      primaryColor: BEColors.primaryColor,
      fontFamily: GoogleFonts.inter().fontFamily,
      textTheme: GoogleFonts.interTextTheme(),
      scaffoldBackgroundColor: BEColors.white,
      secondaryHeaderColor: BEColors.darkBlue,
      popupMenuTheme: PopupMenuThemeData(
        shape: RoundedRectangleBorder(borderRadius: radius(2)),
        menuPadding: EdgeInsets.zero,
      ),
      primarySwatch: createMaterialColor(BEColors.primaryColor),
      bottomSheetTheme: BottomSheetThemeData(
        shape: RoundedRectangleBorder(borderRadius: radiusOnly(topLeft: defaultBERadius, topRight: defaultBERadius)),
      ),
      progressIndicatorTheme: ProgressIndicatorThemeData(color: BEColors.primaryColor),
      textSelectionTheme: TextSelectionThemeData(selectionHandleColor: Colors.transparent),
      pageTransitionsTheme: PageTransitionsTheme(
        builders: {
          TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
          TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
        },
      ),
    );
  }

  String? propertySlug;

  String? propertyHomeGuideSlug;

  Future<void> initDynamicLinks() async {
    if (Platform.isIOS) {
      await Future.delayed(Duration(seconds: 2), () async {
        final data = await FirebaseDynamicLinks.instance.getInitialLink();
        if (data != null) dynamicLinkRedirection(data.link);
      });
    } else {
      final data = await FirebaseDynamicLinks.instance.getInitialLink();
      if (data != null) {
        isSkipSignInScreen = true;
        await dynamicLinkRedirection(data.link);
      }
    }

    // dynamic link launcher listener..
    dynamicLinkRedirectionWhenAppNotKilled();
  }

  Future<void> addHistoryObserver() async {
    //navigation stack observers..
    historyCount = historyObserver.history.length;
    poppedCount = historyObserver.poppedRoutes.length;

    historyObserver.historyChangeStream.listen((change) {
      historyCount = historyObserver.history.length;
      poppedCount = historyObserver.poppedRoutes.length;
      print(" historyCount -- $historyCount , ${historyObserver.history.length}  ||  poppedCount -- $poppedCount  , ${historyObserver.poppedRoutes.length} ");
    });
  }

  Future<void> setStreamChatUserId() async {
    Preferences _preference = Preferences();
    _preference.setStreamChatUserUID(StreamChat.of(App.navigatorKey.currentContext!).currentUser!.id);
  }

  void setUpImagePicker() {
    final configs = ImagePickerConfigs();
    configs.appBarTextColor = Colors.white;
    configs.appBarBackgroundColor = Colors.orange;
    configs.thumbWidth = 70;
    configs.thumbHeight = 70;
    configs.bottomPanelColor = Colors.grey.withOpacity(0.4);
    configs.bottomPanelColorInFullscreen = Colors.grey.withOpacity(0.4);
    configs.translateFunc = (name, value) => Intl.message(value, name: name);

    configs.adjustFeatureEnabled = false;
  }

  void setupGlobalInitialization() {
    try {
      GetIt instance = GetIt.instance;
      instance.registerSingleton<Dio>(Dio());
      instance.registerSingleton<AuthRepository>(AuthRepository());
      instance.registerSingleton(Preferences());
      instance.registerSingleton<String>("$GOOGLE_API_KEY", instanceName: "google_api_key");
    } on Exception catch (e) {
      print(e);
    }
  }

  Future<void> getNotificationDataAndShowNotification(Map<String, dynamic> data) async {
    if (data['type'] == NOTIFICATION_PROFILE_UPDATED || data['type'] == NOTIFICATION_EMAIL_VERIFIED) {
      clickHandle(data);
      return;
    }

    final String messageId = data['message_id'];
    final String channelId = data['channel_id'];
    final String channelType = data['channel_type'];

    Config.appFlavor = Config.appFlavor.name == "staging" ? Staging() : Production();

    await initialize();

    final email = getStringAsync("email");
    final jwtKey = getStringAsync("jwt_token");

    if (App.client.wsConnectionStatus != ConnectionStatus.connected) {
      await App.client.connectUser(User(id: '${email.replaceAll(RegExp(r'[.+]'), "-")}'), jwtKey, connectWebSocket: true).then((value) {}).catchError((e) {});
    }

    // getting channel data from querying the channel...
    final GetMessageResponse message = await App.client.getMessage(messageId.toString());
    ChannelState channelState = await App.client.queryChannel(channelType.toString(), channelId: channelId.toString());

    //getting property_id...
    String propertyId = (channelState.channel!.extraData['tags'] as List).first['propertyId'].toString();
    String propertyName = (channelState.channel!.extraData['tags'] as List).first['propertyName'].toString();

    final int notificationStyle = getIntAsync("notificationTitleStyle");

    NotificationPayload notificationPayload = new NotificationPayload()
      ..channelTitle = AppHelper().setTitleOfNotification(
        type: notificationStyle,
        propertyName: propertyName,
        message: message.message,
      )
      ..message = message.message.text
      ..propertySlug = propertyId
      ..channelType = channelState.channel!.type
      ..messageId = messageId
      ..channelId = channelState.channel!.id;

    AppNotification.showLocalNotification(Random().nextInt(100), notificationPayload);
  }

  void setupNotificationListeners() async {
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
      print("FirebaseMessaging.onMessageOpenedApp ${message.toMap()}");
      if (Platform.isAndroid) {
        clickHandle(message.data);
      } else {
        notificationClickForIOS(message.data);
      }
    });

    FirebaseMessaging.onMessage.listen(
      (RemoteMessage message) async {
        print("FirebaseMessaging.onMessage ${message.toMap()}");
        clickHandle(message.toMap());
      },
    );
  }

  void notificationClickForIOS(Map<String, dynamic> messageData) async {
    if (messageData.isEmpty) {
      print("Empty notification payload");
      return;
    }
    AppNotification.handleNotificationClickIOS(
      data: messageData,
      logNumber: "2",
      isNavigation: true,
    );
  }

  Future<void> clickHandle(Map<String, dynamic> event) async {
    log("data --- notification --- ${event}");
    switch (event['type']) {
      case NOTIFICATION_EMAIL_VERIFIED:
        emailVerified(event);
        break;
      case NOTIFICATION_PROFILE_UPDATED:
        profileUpdate(event);
        break;
      case NOTIFICATION_VERIFY_THIS_EMAIL:
        verifyThisEmail(event);
        break;
      case NOTIFICATION_RESET_PASSWORD:
        resetPassword(event);
        break;
      case NOTIFICATION_CLAIM_PROPERTY:
        claimProperty(event);
        break;
      case NOTIFICATION_CLAIM_PROPERTY_WITHSLUG:
        claimPropertyWithSlugForBackground(event);
        break;
    }
  }

  Future<void> clickHandleKill(Map<String, dynamic> event) async {
    log("data --- notification --- ${event}");
    switch (event['type']) {
      case NOTIFICATION_EMAIL_VERIFIED:
        emailVerified(event);
        break;
      case NOTIFICATION_PROFILE_UPDATED:
        profileUpdate(event);
        break;
      case NOTIFICATION_VERIFY_THIS_EMAIL:
        verifyThisEmail(event);
        break;
      case NOTIFICATION_RESET_PASSWORD:
        resetPassword(event);
        break;
      case NOTIFICATION_CLAIM_PROPERTY:
        claimProperty(event);
        break;
      case NOTIFICATION_CLAIM_PROPERTY_WITHSLUG:
        claimPropertyWithSlugForKill(event);
        break;
    }
  }

  String? notificationBodyMessage({Event? attachments, var message}) {
    if (message == null) {
      if (attachments!.message!.text!.isEmpty) {
        final data = attachments.message!.attachments.first.type;
        if (data == 'image') {
          return '📷' + " " + attachmentMessage(attachments: attachments);
        } else if (data == 'video') {
          return '🎬' + " " + attachmentMessage(attachments: attachments);
        } else if (data == 'giphy') {
          return '[GIF]';
        } else if (data == "file") {
          return "[File] ${attachments.message!.attachments.first.title ?? ""}";
        } else {
          return attachments.message!.text!;
        }
      } else {
        return attachments.message!.text!;
      }
    } else {
      if (message!.text!.isEmpty) {
        final data = message!.attachments.first.type;
        if (data == 'image') {
          return '📷' + " " + attachmentMessage(message: message);
        } else if (data == 'video') {
          return '🎬' + " " + attachmentMessage(message: message);
        } else if (data == 'giphy') {
          return '[GIF]';
        } else if (data == "file") {
          return "[File] ${message!.attachments.first.title ?? ""}";
        } else {
          return message!.text!;
        }
      } else {
        return message!.text!;
      }
    }
  }

  String attachmentMessage({Event? attachments, var message}) {
    if (message == null) {
      final data = attachments!.message!.attachments.first.type;
      if (data == 'image') {
        return 'image';
      } else if (data == 'video') {
        return 'video';
      } else {
        return '';
      }
    } else {
      final data = message!.attachments.first.type;
      if (data == 'image') {
        return 'image';
      } else if (data == 'video') {
        return 'video';
      } else {
        return '';
      }
    }
  }

  String setTitleOfNotification({required int type, Event? event, var message, required String propertyName}) {
    if (message == null) {
      switch (type) {
        case 1:
          return propertyName;
        case 2:
          return "${event!.message!.user!.name}";
        case 3:
          return "${event!.message!.user!.name}";
        default:
          return "${event!.message!.user!.name}";
      }
    } else {
      switch (type) {
        case 1:
          return propertyName;
        case 2:
          return "${message!.user!.name}";
        case 3:
          return "${message!.user!.name}";
        default:
          return "${message!.user!.name}";
      }
    }
  }

  String setBodyOfNotification({required int type, Event? event, var message, required String propertyName}) {
    if (message == null) {
      switch (type) {
        case 1:
          return "user : ${notificationBodyMessage(attachments: event)}";
        case 2:
          if (event!.message!.text.isNotNullOrEmpty()) {
            if (event.message!.text!.startsWith('*') && event.message!.text!.endsWith('*')) {
              return event.message!.text!.replaceAll("*", "");
            } else if (event.message!.text!.startsWith('**') && event.message!.text!.endsWith('**')) {
              return event.message!.text!.replaceAll("**", "");
            } else if (event.message!.text!.startsWith('~') && event.message!.text!.endsWith('~')) {
              return event.message!.text!.replaceAll("~", "");
            } else if (event.message!.text!.startsWith('<u>')) {
              return event.message!.text!.replaceAll(RegExp(r'^<u>|</u>$'), '');
            } else {
              return event.message!.text!;
            }
          }
          return "$propertyName : ${notificationBodyMessage(attachments: event)}";
        case 3:
          return '${notificationBodyMessage(attachments: event)}';
        default:
          return '${notificationBodyMessage(attachments: event)}';
      }
    } else {
      switch (type) {
        case 1:
          return "user : ${notificationBodyMessage(message: message)}";
        case 2:
          if (event!.message!.text.isNotNullOrEmpty()) {
            if (event.message!.text!.startsWith('*') && event.message!.text!.endsWith('*')) {
              return event.message!.text!.replaceAll("*", "");
            } else if (event.message!.text!.startsWith('**') && event.message!.text!.endsWith('**')) {
              return event.message!.text!.replaceAll("**", "");
            } else if (event.message!.text!.startsWith('~') && event.message!.text!.endsWith('~')) {
              return event.message!.text!.replaceAll("~", "");
            } else if (event.message!.text!.startsWith('<u>')) {
              return event.message!.text!.replaceAll(RegExp(r'^<u>|</u>$'), '');
            } else {
              return event.message!.text!;
            }
          }
          return "$propertyName : ${notificationBodyMessage(message: message)}";
        case 3:
          return '${notificationBodyMessage(message: message)}';
        default:
          return '${notificationBodyMessage(message: message)}';
      }
    }
  }

  Future<void> setNotificationTitleStyle() async {
    final preferences = GetIt.instance<Preferences>();
    switch (notificationStyleTheme) {
      case 1:
        await preferences.setNotificationStyle(1);
        break;
      case 2:
        await preferences.setNotificationStyle(2);
        break;
      case 3:
        await preferences.setNotificationStyle(3);
        break;
      default:
        await preferences.setNotificationStyle(1);
        break;
    }
  }

  static List<int> getYear() {
    final currentYear = DateTime.now().year;
    return List<int>.generate(currentYear - 2009, (index) => 2010 + index);
  }

  void emailVerified(Map<String, dynamic> event) {
    controller.sink.add(event);
    print("------------------email verified-------------------");
  }

  void profileUpdate(Map<String, dynamic> event) {
    controller.sink.add(event);
    print("------------------profile updated-------------------");
  }

  Future<Widget> _buildUserVerificationView() async {
    final preferences = GetIt.instance<Preferences>();
    final email = await preferences.getEmail();
    final jwtKey = await preferences.getJWTToken();

    return UserVerificationView(
      userEmail: email,
      isVerified: true,
      jwtKey: jwtKey,
    );
  }

  void navigateToVerification(BuildContext context) {
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(
        builder: (context) {
          return FutureBuilder(
            future: _buildUserVerificationView(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(child: CircularProgressIndicator());
              } else if (snapshot.hasError) {
                return Center(child: Text('Error: ${snapshot.error}'));
              } else {
                return snapshot.data as Widget;
              }
            },
          );
        },
      ),
    );
  }

  Future<void> verifyThisEmail(Map<String, dynamic> event) async {
    print("------------------verify email-------------------");
    Map<String, dynamic> data = {'confirmation_token': event['confirm_password_token']};
    final result = await AuthRepository().verifyThisEmail(data);
    print("property slug:-  ${event["property_slug"]}");
    String? propertySlug = event["property_slug"];
    final preferences = GetIt.instance<Preferences>();
    bool? verified = await preferences.getIsEmailVerified();
    result.when(onSuccess: (s) async {
      if (s.data == null) {
        if (verified == true) {
          print("isVerified if data null if condition :- ${await preferences.getIsEmailVerified()}");
          final email = await preferences.getEmail();
          final jwtKey = await preferences.getJWTToken();
          Navigator.of(App.navigatorKey.currentContext!).pushReplacement(
            MaterialPageRoute(
              builder: (context) {
                return UserVerificationView(
                  userEmail: email,
                  isVerified: verified,
                  jwtKey: jwtKey,
                );
              },
            ),
          );
        } else {
          print("isVerified if data null else condition :- ${await preferences.getIsEmailVerified()}");
          final email = await preferences.getEmail();
          final verified = await preferences.getIsEmailVerified();
          final jwtKey = await preferences.getJWTToken();
          if (jwtKey.validate().isNotEmpty && verified == true) {
            Navigator.of(App.navigatorKey.currentContext!).pushReplacement(
              MaterialPageRoute(
                builder: (context) {
                  return UserVerificationView(
                    userEmail: email,
                    isVerified: true,
                    jwtKey: jwtKey,
                  );
                },
              ),
            );
          } else {
            if (verified == true) {
              Navigator.of(App.navigatorKey.currentContext!).pushReplacement(
                MaterialPageRoute(
                  builder: (context) {
                    return UserVerificationView(
                      userEmail: email,
                      isVerified: true,
                      jwtKey: jwtKey,
                    );
                  },
                ),
              );
            }
          }
        }
        return;
      } else {
        /// check this email is the same as ours...
        final preferences = GetIt.instance<Preferences>();
        final email = await preferences.getEmail();

        if (email.toString() == s.data!.email) {
          Map<String, dynamic> typeData = {'type': NOTIFICATION_VERIFY_THIS_EMAIL};
          event.addAll(typeData);
          controller.sink.add(event);
        } else {
          // logging out old user...
          //await ApiClient().clearDataAndPerformLogout(wantNavigation: false);
          try {
            //New user login changes...
            await AppHelper().connectWithGetStream(s);
          } on Exception catch (e) {
            print(e.toString());
          } finally {
            if (s.data!.userServiceCategories != null && s.data!.organization != null) {
              s.data!.userServiceCategories = s.userServiceCategories;
              s.data!.organization = s.organization;
            }
            if (s.message == "Your email address has been successfully confirmed.") {
              final email = await preferences.getEmail();
              final verified = await preferences.getIsEmailVerified();
              final jwtKey = await preferences.getJWTToken();
              if (propertySlug.validate().isNotEmpty) {
                getAllPropertyInfo(propertySlug.toString());
              } else {
                Navigator.of(App.navigatorKey.currentContext!).pushReplacement(
                  MaterialPageRoute(
                    builder: (context) {
                      return UserVerificationView(
                        userEmail: s.data!.verificationUser!.email,
                        isVerified: s.data!.verificationUser!.verified,
                        jwtKey: jwtKey,
                        isEmailConfirmed: true,
                      );
                    },
                  ),
                );
              }
            }
            await saveUserDataInPreference(
              s.header!,
              s.data!.email ?? "",
              s.data!.name ?? "",
              s.data!.profileImage ?? "",
              s.data!.getStreamJwtToken!,
              s.verified!,
              s.data!,
              s.accountType ?? "",
              s.data!.isOrgCreator!,
            );
            setUpDio(s.header!);
            if (s.data!.status! == "pending") {
              await preferences.setMembershipRequestStatus(true);
              App.navigatorKey.currentState!.pushReplacementNamed(MemberRequestPendingScreen.route);
            } else {
              //redirection
              String? value = await preferences.getAccountType();
              if (value != null) {
                if (value == "company" || value == "proprietor" || value == "organization") {
                  RegisterInGetIt<SignUpOnBoardViewModel>(SignUpOnBoardViewModel(), name: "signUpOnBoardViewModel");
                  if (s.message == "Confirmed Successfully..!") {
                    print("isVerified after confirmed:- ${await preferences.getIsEmailVerified()}");
                    print("jwtKey :- ${await preferences.getJWTToken()}");
                    final email = await preferences.getEmail();
                    final verified = await preferences.getIsEmailVerified();
                    final jwtKey = await preferences.getJWTToken();
                    if (propertySlug.validate().isNotEmpty) {
                      getAllPropertyInfo(propertySlug.toString());
                    } else {
                      Navigator.of(App.navigatorKey.currentContext!).pushReplacement(
                        MaterialPageRoute(
                          builder: (context) {
                            return UserVerificationView(userEmail: email, isVerified: verified, jwtKey: jwtKey, accountType: value);
                          },
                        ),
                      );
                    }
                  }
                } else {
                  App.navigatorKey.currentState!.pushNamedAndRemoveUntil(DashBoardScreen.route, (route) => false, arguments: true);
                }
              } else {
                App.navigatorKey.currentState!.pushNamedAndRemoveUntil(DashBoardScreen.route, (route) => false, arguments: true);
              }
            }
          }
        }
        if (s.message == "Confirmed Successfully..!") {
          print("isVerified after confirmed:- ${await preferences.getIsEmailVerified()}");
          print("jwtKey :- ${await preferences.getJWTToken()}");
          final email = await preferences.getEmail();
          final verified = await preferences.getIsEmailVerified();
          final jwtKey = await preferences.getJWTToken();
          if (propertySlug.validate().isNotEmpty) {
            getAllPropertyInfo(propertySlug.toString());
          } else {
            Navigator.of(App.navigatorKey.currentContext!).pushReplacement(
              MaterialPageRoute(
                builder: (context) {
                  return UserVerificationView(
                    userEmail: email,
                    isVerified: verified,
                    jwtKey: jwtKey,
                  );
                },
              ),
            );
          }
        }
        toast(s.message ?? "Email verified!");
      }
    }, onError: (e) {
      toast(e.toString());
    });
  }

  Future<void> saveUserDataInPreference(CurrentUserDetails userDetails, String email, String name, String profile, String jwtToken, bool verified, Data data, String accountType, [bool? isOrgCreator]) async {
    Preferences preference = Preferences();
    await preference.saveUserData(userDetails);
    await preference.setName(name);
    await preference.setEmail(email);
    await preference.setUserID(data.id!);
    await preference.setProfile(profile);
    await preference.setJWTToken(jwtToken);
    await preference.setFlavor(Config.appFlavor.name.toString());
    await preference.setEmailVerified(verified);
    await preference.setUserServices(data.userServiceCategories ?? []);
    await preference.setAccountType(accountType);
    await preference.setOrganizationSlug(data.organization);
    await preference.setOrgCreator(data.isOrgCreator!);
    await preference.setRole(data.role ?? "");

    await AppHelper().setNotificationTitleStyle();
  }

  Future<void> connectWithGetStream(SignInResponse s) async {
    /* try {
      print("Check point 2");
      if (App.client.wsConnectionStatus != ConnectionStatus.disconnected) {
        await App.client.disconnectUser();
      }
    } on Exception catch (e) {
      print("Check point 3");
      print(e.toString());
    }*/

    OwnUser user = await App.client.connectUser(
      User(id: '${s.data!.uid!.replaceAll(RegExp(r'[.+]'), '-')}', name: s.data!.name),
      s.data!.getStreamJwtToken!,
    );

    App.client.openPersistenceConnection(user);

    // setUpForegroundNotifications();
    try {
      AppHelper().registerFirebaseTokenToBackend();
    } catch (e) {
      print("-----------${e}");
    }
  }

  void resetPassword(Map<String, dynamic> event) async {
    await 1.seconds.delay;
    toast("reset password...!");
    App.navigatorKey.currentState!.pop();
    App.navigatorKey.currentState!.pushNamed(ResetPasswordScreen.route, arguments: event['reset_password_token']);
  }

  void setUpDio(CurrentUserDetails userDetails) {
    final user = userDetails;

    if (GetIt.instance.isRegistered<Dio>()) {
      GetIt.instance.unregister<Dio>();
    }

    Dio dio = Dio(
      BaseOptions(
        baseUrl: Config.appFlavor.url + "api/v1/",
        contentType: Headers.formUrlEncodedContentType,
        headers: {'access-token': user.accessToken, 'client': user.client, 'uid': user.uid, 'token_type': user.tokenType, 'expiry': user.expiry},
      ),
    );

    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        print("request");
      },
      onResponse: (e, handler) {
        if (e.statusCode == Exceptions.forceLogoutExceptionCode) {
          final preference = GetIt.instance<Preferences>();
          preference.clearUserData();
          App.navigatorKey.currentState!.pushNamedAndRemoveUntil(SignInScreen.route, (Route<dynamic> route) => false);
        }
      },
      onError: (e, handler) {
        if (e.response?.statusCode == Exceptions.forceLogoutExceptionCode) {
          final preference = GetIt.instance<Preferences>();
          preference.clearUserData();
          App.navigatorKey.currentState!.pushNamedAndRemoveUntil(SignInScreen.route, (Route<dynamic> route) => false);
        }
      },
    ));

    // RegisterInGetIt<Dio>(dio, name: "user_api_dio");
  }

  void claimProperty(Map<String, dynamic> event) async {
    // Map<String, dynamic> typeData = {'type': NOTIFICATION_CLAIM_PROPERTY};
    // event.addAll(typeData);    await 1.seconds.delay;
    await 1.seconds.delay;

    toast("Claim Property...!");
    App.navigatorKey.currentState!.pushNamed(ClaimPropertyScreen.route, arguments: propertySlug ?? "");
  }

  OwnProperty? myProperty;

  Future<OwnProperty?> getAllPropertyInfo(
    String slug, {
    String? unitId,
    String? spaceSlug,
    String? spaceZoneId,
    bool? isFromKill,
    String? productCategoryHeadingId,
    String? productCategoryHeadingName,
    String? parentProductCategoryHeadingName,
    String? productTypeId,
    String? productTypeName,
    String? finishCategoryHeadingName,
    String? isFinish,
    String? unitSpaceId,
    String? unitSpaceName,
    String? parentUnitSpaceName,
    ApiState apiStateView = ApiState.running,
  }) async {
    /* if (myProperty != null) {
      return Future.value(myProperty);
    }*/
    final preference = GetIt.instance<Preferences>();
    final user = await preference.getUserDetails();
    if (user.client.isNullOrEmpty()) {
      toast("You need to sign in or sign up before continuing.");
      // Toast(App.navigatorKey.currentContext!).showErrorToast('You need to sign in or sign up before continuing.');
      print('-------------Empty Toast');
    } else {
      final result = await CreatePropertyRepository().getPropertyAllInfo('$slug');
      result.when(onSuccess: (s) async {
        if (result.data != null && result.data!.myProperty != null) {
          OwnProperty ownProperty = new OwnProperty()
            ..slug = result.data!.myProperty!.slug.toString()
            ..name = result.data!.myProperty!.name
            ..id = result.data!.myProperty!.id
            ..address = result.data!.myProperty!.addressText
            ..buildingCounts = result.data!.myProperty!.buildings!.length;
          myProperty = ownProperty;
          bool? isChatEnable = result.data?.myProperty?.isChatEnable;
          int? propertyId = result.data!.myProperty!.id;
          getInteriorListData(spaceZoneId: spaceZoneId, unitID: unitId, spaceSlugFromUrl: spaceSlug);
          if (isFromKill.validate()) {
            handlePropertyScanSlug(slug,
                propertyId: propertyId,
                propertyName: result.data!.myProperty!.name,
                unitId: unitId,
                spaceSlug: spaceSlug,
                spaceZoneId: spaceZoneId,
                isFromKill: true,
                productCategoryHeadingId: productCategoryHeadingId,
                productCategoryHeadingName: productCategoryHeadingName,
                parentProductCategoryHeadingName: parentProductCategoryHeadingName,
                productTypeId: productTypeId,
                productTypeName: productTypeName,
                finishCategoryHeadingName: finishCategoryHeadingName,
                isFinish: isFinish,
                unitSpaceId: unitSpaceId,
                unitSpaceName: unitSpaceName,
                parentUnitSpaceName: parentUnitSpaceName,
                isChatEnable: isChatEnable);
          } else {
            handlePropertyScanSlug(
              slug,
              propertyId: propertyId,
              propertyName: result.data!.myProperty!.name,
              unitId: unitId,
              spaceSlug: spaceSlug,
              spaceZoneId: spaceZoneId,
              isFromKill: false,
              productCategoryHeadingId: productCategoryHeadingId,
              productCategoryHeadingName: productCategoryHeadingName,
              parentProductCategoryHeadingName: parentProductCategoryHeadingName,
              productTypeId: productTypeId,
              productTypeName: productTypeName,
              finishCategoryHeadingName: finishCategoryHeadingName,
              isFinish: isFinish,
              unitSpaceId: unitSpaceId,
              unitSpaceName: unitSpaceName,
              parentUnitSpaceName: parentUnitSpaceName,
              isChatEnable: isChatEnable,
            );
          }
          //RegisterInGetIt<OwnProperty>(myProperty, name: "selected_property");
          //RegisterInGetIt<String>(propertySlug, name: "selected_property_slug");
          return ownProperty;
        }
      }, onError: (e) async {
        toast(e.toString());
        App.navigatorKey.currentState!.pushReplacementNamed(DashBoardScreen.route);
      });
    }
    return null;
  }

  Future<void> handlePropertyScanSlug(
    String propertySlug, {
    String? unitId,
    String? propertyName,
    String? spaceSlug,
    String? spaceZoneId,
    bool? isFromKill,
    String? productCategoryHeadingId,
    String? productCategoryHeadingName,
    String? parentProductCategoryHeadingName,
    String? productTypeId,
    String? productTypeName,
    String? finishCategoryHeadingName,
    String? isFinish,
    String? unitSpaceId,
    String? unitSpaceName,
    String? parentUnitSpaceName,
    bool? isChatEnable,
    int? propertyId,
  }) async {
    RegisterInGetIt<OwnProperty>(OwnProperty(slug: propertySlug), name: "selected_property");
    RegisterInGetIt<String>(propertySlug, name: "selected_property_slug");

    //await getSpaceZoneList({"property_slug": propertySlug});
    GetIt.instance<OwnProperty>(instanceName: "selected_property").id = propertyId;
    if (spaceSlug.validate().isNotEmpty) {
      finish(App.navigatorKey.currentContext!);
      if (isFromKill.validate()) {
        Navigator.of(App.navigatorKey.currentContext!).pushAndRemoveUntil(
          MaterialPageRoute(
            builder: (context) => SpaceSummaryNewScreen(isFromQrScan: true, unitSlug: unitId, unitSpaceSlug: spaceSlug, propertyName: propertyName, isFromKill: true, isChatEnable: isChatEnable),
          ),
          (Route<dynamic> route) => false, // Adjust the condition as needed
        );
      } else {
        await SpaceSummaryNewScreen(
          isFromQrScan: true,
          unitSlug: unitId,
          unitSpaceSlug: spaceSlug,
          propertyName: propertyName,
          isChatEnable: isChatEnable,
        ).launch(App.navigatorKey.currentContext!);
      }
    } else {
      await showProductAggregationSpaceData(unitId: unitId, spaceZoneId: spaceZoneId);
      await showProductListFinishesListData(unitId: unitId, spaceZoneId: spaceZoneId);
      await showProductAggregationCategoryData(unitId: unitId, spaceZoneId: spaceZoneId);
      finish(App.navigatorKey.currentContext!);

      if (isFromKill.validate()) {
        Navigator.of(App.navigatorKey.currentContext!).pushAndRemoveUntil(
          MaterialPageRoute(
            builder: (context) => ProductAggregationListScreen(
                productTypeId: productTypeId,
                unitId: unitId,
                unitSpaceID: unitSpaceId,
                productListTitlePojo: ProductListTitlePojo(
                    title: isFinish.validate().isNotEmpty
                        ? productTypeName.validate()
                        : unitSpaceName.validate().isNotEmpty
                            ? unitSpaceName.validate()
                            : productCategoryHeadingName.validate(),
                    subTitle: parentProductCategoryHeadingName.validate().isNotEmpty
                        ? parentProductCategoryHeadingName.validate()
                        : isFinish.validate().isNotEmpty
                            ? finishCategoryHeadingName.validate()
                            : parentUnitSpaceName.validate().isNotEmpty
                                ? parentUnitSpaceName.validate()
                                : "",
                    slug: productCategoryHeadingId.validate(),
                    isUnitFinishProductsAggregation: productTypeId.validate().isEmptyOrNull ? null : true,
                    isProductAggregationBySpace: unitSpaceId.validate().isEmptyOrNull ? false : true),
                propertyName: myProperty?.name,
                isFromQrScan: true,
                isFromKill: true),
          ),
          (Route<dynamic> route) => false, // Adjust the condition as needed
        );
        isFromDynamicLink = false;
      } else {
        await ProductAggregationListScreen(
                productTypeId: productTypeId,
                unitId: unitId,
                unitSpaceID: unitSpaceId,
                productListTitlePojo: ProductListTitlePojo(
                    title: isFinish.validate().isNotEmpty
                        ? productTypeName.validate()
                        : unitSpaceName.validate().isNotEmpty
                            ? unitSpaceName.validate()
                            : productCategoryHeadingName.validate(),
                    subTitle: parentProductCategoryHeadingName.validate().isNotEmpty
                        ? parentProductCategoryHeadingName.validate()
                        : isFinish.validate().isNotEmpty
                            ? finishCategoryHeadingName.validate()
                            : parentUnitSpaceName.validate().isNotEmpty
                                ? parentUnitSpaceName.validate()
                                : "",
                    slug: productCategoryHeadingId.validate(),
                    isUnitFinishProductsAggregation: productTypeId.validate().isEmptyOrNull ? null : true,
                    isProductAggregationBySpace: unitSpaceId.validate().isEmptyOrNull ? false : true),
                propertyName: myProperty?.name,
                isFromQrScan: true)
            .launch(App.navigatorKey.currentContext!);
      }
    }
  }

  Future<void> showProductAggregationSpaceData({ApiState apiStateStatus = ApiState.running, String? spaceZoneId, String? unitId}) async {
    final interiorRepo = ProductRepository();
    //showProductAggregationApiState = apiStateStatus;

    getProductAggregationSpaceList.clear();

    final result = await interiorRepo.showProductAggregationSpaceData(
      propertyId: '${GetIt.instance<String>(instanceName: "selected_property_slug")}',
      spaceZoneId: spaceZoneId,
      unitId: unitId,
    );

    result.when(onSuccess: (s) {
      getProductAggregationSpaceList = s.validate().asObservable();

      //showProductAggregationApiState = ApiState.success;
    }, onError: (e) {
      if (ApiClient.preventApiCallTeamMemberDelete < 1) {
        toast(e.toString());
      }
      showProductAggregationApiState = ApiState.error;
    });
  }

  Future<void> showProductListFinishesListData({ApiState apiStateStatus = ApiState.running, String? unitId, String? spaceZoneId}) async {
    final interiorRepo = ProductRepository();
    //showProductAggregationApiState = apiStateStatus;

    final result = await interiorRepo.showProductListFinishesListData(
      unitId: unitId,
      spaceZoneId: spaceZoneId,
      isFinish: "true",
    );

    result.when(onSuccess: (s) {
      showProductListFinishesList.clear();
      showProductListFinishesList.addAll(s.productListFinishHeading!);

      //showProductAggregationApiState = ApiState.success;
    }, onError: (e) {
      if (ApiClient.preventApiCallTeamMemberDelete < 1) {
        toast(e.toString());
      }
      showProductAggregationApiState = ApiState.error;
    });
  }

  Future<void> showProductAggregationCategoryData({ApiState apiStateStatus = ApiState.running, String? spaceZoneId, String? unitId}) async {
    final interiorRepo = ProductRepository();
    //showProductAggregationApiState = apiStateStatus;

    final result = await interiorRepo.showProductAggregationData(
      propertySlug: '${GetIt.instance<String>(instanceName: "selected_property_slug")}',
      spaceZoneId: spaceZoneId,
      withFinishes: "true",
      unitId: unitId,
    );

    result.when(onSuccess: (s) {
      productHoldings = null;
      productHoldings = s.productHoldings;

      //showProductAggregationApiState = ApiState.success;
    }, onError: (e) {
      if (ApiClient.preventApiCallTeamMemberDelete < 1) {
        toast(e.toString());
      }
      showProductAggregationApiState = ApiState.error;
    });
  }

  Future<void> getSpaceZoneList(Map<String, dynamic> params) async {
    final interiorRepo = SpaceRepository();
    if (getSpaceListZoneApiState != ApiState.running) {
      getSpaceListZoneApiState = ApiState.running;
      final result = await interiorRepo.getSpaceZoneList(params);
      result.when(onSuccess: (s) {
        if (s.data == null) {
          getSpaceListZoneApiState = ApiState.error;
          return;
        }
        spaceZoneListModel = s;
        selectedSpaceZoneId = spaceZoneListModel!.data!.first.name!.toLowerCase();
        getSpaceListZoneApiState = ApiState.success;
      }, onError: (e) {
        if (ApiClient.preventApiCallTeamMemberDelete < 1) {
          toast(e.toString());
        }
        getSpaceListZoneApiState = ApiState.error;
      });
    }
  }

  Future<void> getInteriorListData({ApiState apiStateStatus = ApiState.running, String? spaceZoneId, String? unitID, String? spaceSlugFromUrl}) async {
    final interiorRepo = SpaceRepository();
    if (getSpaceListDataApiState != ApiState.running) {
      getSpaceListDataApiState = apiStateStatus;

      final result = await interiorRepo.getSpaceInterior(unitID: unitID!, spaceZoneId: spaceZoneId!);

      result.when(onSuccess: (s) async {
        if (s.data == null && s.data!.unitSpacesFloorWise.isNullOrEmpty()) {
          getSpaceListDataApiState = ApiState.error;
          return;
        }

        if (spaceInteriorInfoList.isEmpty) {
          if (s.data!.unitSpacesFloorWise!.isNotEmpty) {
            if (!s.data!.unitSpacesFloorWise!.first.unitSpaces.isNullOrEmpty()) {
              registerUnitSpace(s.data!.unitSpacesFloorWise!.first.unitSpaces!.first);
            }
          }
        }

        spaceInteriorInfoList.clear();
        spaceInteriorInfoList.addAll(s.data!.unitSpacesFloorWise!);

        for (var floor in s.data!.unitSpacesFloorWise!) {
          if (floor.unitSpaces != null && floor.unitSpaces!.isNotEmpty) {
            for (var unitSpace in floor.unitSpaces!) {
              // Check if spaceSlug matches unitSpace.slug
              if (unitSpace.slug == spaceSlugFromUrl) {
                final int? productCount = unitSpace.productsCount;

                if (productCount != null) {
                  GetIt.instance<UnitSpace>(instanceName: "selected_unit_space").productsCount = productCount;
                } else {}
              }

              // Check if spaceSlug matches any childUnitSpaces.slug
              if (!unitSpace.childUnitSpaces.isNullOrEmpty()) {
                for (var childUnitSpace in unitSpace.childUnitSpaces!) {
                  if (childUnitSpace.slug == spaceSlugFromUrl) {
                    final int? productCount = childUnitSpace.productsCount;

                    if (productCount != null) {
                      GetIt.instance<UnitSpace>(instanceName: "selected_unit_space").productsCount = productCount;
                    }
                    break;
                  } else {
                    if (!childUnitSpace.childUnitSpaces.isNullOrEmpty()) {
                      for (var grandChildUnitSpace in childUnitSpace.childUnitSpaces!) {
                        if (grandChildUnitSpace.slug == spaceSlugFromUrl) {
                          final int? productCount = grandChildUnitSpace.productsCount;

                          if (productCount != null) {
                            GetIt.instance<UnitSpace>(instanceName: "selected_unit_space").productsCount = productCount;
                          }
                          break; // Exit loop after finding the match
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }

        getSpaceListDataApiState = ApiState.success;

        s.propertyId = GetIt.instance<OwnProperty>(instanceName: "selected_property").id!;
        s.unitId = unitID.validate();
      }, onError: (e) {
        getSpaceListDataApiState = ApiState.error;
        if (ApiClient.preventApiCallTeamMemberDelete < 1) {
          toast(e.toString());
        }
        print("${e.toString()}");
      });
    }
  }

  void registerUnitSpace(UnitSpace value) async {
    RegisterInGetIt<UnitSpace>(value, name: "selected_unit_space");
  }

  Future<void> claimPropertyWithSlugForBackground(Map<String, dynamic> event) async {
    String? unitId = event["unit_id"] ?? "";
    String? spaceSlug = event["space_slug"] ?? "";
    String? spaceZoneId = event["space_zone_id"] ?? "";

    String productCategoryHeadingId = event['product_category_heading_id'] ?? "";
    String productCategoryHeadingName = event['product_category_heading_name'] ?? "";
    String parentProductCategoryHeadingName = event['parent_product_category_heading_name'] ?? "";
    String productTypeId = event['product_type_id'] ?? "";
    String productTypeName = event['product_type_name'] ?? "";
    String finishCategoryHeadingName = event['finish_category_heading_name'] ?? "";
    String isFinish = event['is_finish'] ?? "";
    String unitSpaceId = event['unit_space_id'] ?? "";
    String unitSpaceName = event['unit_space_name'] ?? "";
    String parentUnitSpaceName = event['parent_unit_space_name'] ?? "";

    if (spaceSlug.validate().isNotEmpty) {
      String? unitSlug = event["unit_slug"] ?? "";
      await getAllPropertyInfo(propertyHomeGuideSlug!, unitId: unitSlug, spaceSlug: spaceSlug, spaceZoneId: spaceZoneId, isFromKill: false);
    } else {
      await getAllPropertyInfo(propertyHomeGuideSlug!,
          unitId: unitId,
          spaceZoneId: spaceZoneId,
          productCategoryHeadingId: productCategoryHeadingId,
          productCategoryHeadingName: productCategoryHeadingName,
          parentProductCategoryHeadingName: parentProductCategoryHeadingName,
          productTypeId: productTypeId,
          productTypeName: productTypeName,
          finishCategoryHeadingName: finishCategoryHeadingName,
          isFinish: isFinish,
          unitSpaceId: unitSpaceId,
          unitSpaceName: unitSpaceName,
          parentUnitSpaceName: parentUnitSpaceName,
          apiStateView: ApiState.running,
          isFromKill: false);
    }

    //RegisterInGetIt<OwnProperty>(myProperty, name: "selected_property");

    //RegisterInGetIt<OwnProperty>(myProperty, name: "selected_property");
    //RegisterInGetIt<String>(propertySlug, name: "selected_property_slug");
  }

  Future<void> claimPropertyWithSlugForKill(Map<String, dynamic> event) async {
    String? unitId = event["unit_id"] ?? "";
    String? spaceSlug = event["space_slug"] ?? "";
    String? spaceZoneId = event["space_zone_id"] ?? "";

    String productCategoryHeadingId = event['product_category_heading_id'] ?? "";
    String productCategoryHeadingName = event['product_category_heading_name'] ?? "";
    String parentProductCategoryHeadingName = event['parent_product_category_heading_name'] ?? "";
    String productTypeId = event['product_type_id'] ?? "";
    String productTypeName = event['product_type_name'] ?? "";
    String finishCategoryHeadingName = event['finish_category_heading_name'] ?? "";
    String isFinish = event['is_finish'] ?? "";
    String unitSpaceId = event['unit_space_id'] ?? "";
    String unitSpaceName = event['unit_space_name'] ?? "";
    String parentUnitSpaceName = event['parent_unit_space_name'] ?? "";

    if (spaceSlug.validate().isNotEmpty) {
      String? unitSlug = event["unit_slug"] ?? "";
      Config.appFlavor = Config.appFlavor.name == "staging" ? Staging() : Production();
      final String email = getStringAsync("email");
      final String jwtKey = getStringAsync("jwt_token");
      print("App.client.wsConnectionStatus != ConnectionStatus.connected" + " ======> " + "${App.client.wsConnectionStatus}");

      if (App.client.wsConnectionStatus != ConnectionStatus.connected) {
        try {
          print("email" + " ======> " + "${email.replaceAll(RegExp(r'[.+]'), "-")}");
          print("jwtKey" + " ======> " + "${jwtKey}");

          if (jwtKey.isEmpty && email.isEmpty) {
            await getAllPropertyInfo(propertyHomeGuideSlug!, unitId: unitSlug, spaceSlug: spaceSlug, spaceZoneId: spaceZoneId, isFromKill: true);
            //SignInScreen().launch(App.navigatorKey.currentState!.context);
          } else {
            await App.client.connectUser(
              User(id: '${email.replaceAll(RegExp(r'[.+]'), "-")}'),
              jwtKey,
              connectWebSocket: false,
            );
            await getAllPropertyInfo(propertyHomeGuideSlug!, unitId: unitSlug, spaceSlug: spaceSlug, spaceZoneId: spaceZoneId, isFromKill: true);
          }
        } on Exception catch (e) {
          print("e" + " ======> " + "${e}");
        }
        print("User connected");
      }
    } else {
      await getAllPropertyInfo(propertyHomeGuideSlug!,
          unitId: unitId,
          spaceZoneId: spaceZoneId,
          productCategoryHeadingId: productCategoryHeadingId,
          productCategoryHeadingName: productCategoryHeadingName,
          parentProductCategoryHeadingName: parentProductCategoryHeadingName,
          productTypeId: productTypeId,
          productTypeName: productTypeName,
          finishCategoryHeadingName: finishCategoryHeadingName,
          isFinish: isFinish,
          unitSpaceId: unitSpaceId,
          unitSpaceName: unitSpaceName,
          parentUnitSpaceName: parentUnitSpaceName,
          apiStateView: ApiState.running,
          isFromKill: true);
      /*SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('propertySlug', propertyHomeGuideSlug!);*/
    }
  }

  Future<String> getSingleImageFromCameraOrGallery() async {
    List<String> imageList = [];
    final List<ImageObject>? objects = await Navigator.of(App.navigatorKey.currentContext!).push(
      PageRouteBuilder(
        pageBuilder: (context, animation, __) {
          return ImagePicker(maxCount: 1, isFullscreenImage: true, needBottomSelection: true);
        },
      ),
    );
    if ((objects?.length ?? 0) > 0) {
      objects!.forEach((element) {
        print("Original Path : ${element.originalPath}  Modified Path : ${element.modifiedPath}");
        imageList.add(element.modifiedPath);
      });
    }
    return imageList.first;
  }

  void dynamicLinkRedirectionWhenAppNotKilled() {
    dynamicLinks.onLink.listen((dynamicLinkData) async {
      print("link launching -- -- -- - ${dynamicLinkData.link}\n${dynamicLinkData.link.data.toString()}");
      if (dynamicLinkData.link.toString().contains('confirm-account')) {
        /// Handling confirm Account...
        /*final preference = GetIt.instance<Preferences>();
        final token = await preference.getUserToken();
        final emailVerified = await preference.getIsEmailVerified();*/

        // if (!token.isNullOrEmpty()) {
        // if (!(emailVerified ?? false)) {
        Map<String, dynamic> data = {'type': NOTIFICATION_VERIFY_THIS_EMAIL};
        data.addAll(dynamicLinkData.link.queryParameters);
        clickHandle(data);
        // App.navigatorKey.currentState!.pushNamed(EmailVerificationScreen.route);
        // }
        // }
      } else if (dynamicLinkData.link.toString().contains('reset-password')) {
        /// Handling reset password...
        Map<String, dynamic> data = {'type': NOTIFICATION_RESET_PASSWORD};
        data.addAll(dynamicLinkData.link.queryParameters);
        clickHandle(data);
      } else if (dynamicLinkData.link.toString().contains('claim-your-homeguide')) {
        /// Claim Your Homeguide...

        if (dynamicLinkData.link.toString().contains('claim-your-homeguide?property_slug')) {
          propertySlug = dynamicLinkData.link.queryParameters['property_slug'];
          Map<String, dynamic> data = {'type': NOTIFICATION_CLAIM_PROPERTY};
          data.addAll(dynamicLinkData.link.queryParameters);
          clickHandle(data);
        } else {
          propertySlug = "";
          Map<String, dynamic> data = {'type': NOTIFICATION_CLAIM_PROPERTY};
          data.addAll(dynamicLinkData.link.queryParameters);
          clickHandle(data);
        }
      } else if (dynamicLinkData.link.toString().contains('workarea')) {
        /// Claim Your Homeguide with slug...
        ///
        // /propertyHomeGuideSlug = dynamicLinkData.link.toString().split('workarea/')[1].split('/homeguide')[0];
        propertyHomeGuideSlug = dynamicLinkData.link.toString().split('workarea/')[1].split('/virtualhome')[0];
        if (dynamicLinkData.link.toString().contains('workarea/$propertyHomeGuideSlug/homeguide')) {
          Map<String, dynamic> data = {'type': NOTIFICATION_CLAIM_PROPERTY_WITHSLUG};
          data.addAll(dynamicLinkData.link.queryParameters);
          await clickHandle(data);
        } else {
          if (dynamicLinkData.link.toString().contains('space_slug')) {
            final qrUri = Uri.parse(dynamicLinkData.link.toString());
            String? propertySlug = qrUri.queryParameters['property_slug'];
            String? unitSlug = qrUri.queryParameters['unit_slug'];
            String? spaceSlug = qrUri.queryParameters['space_slug'];
            String? spaceZoneID = qrUri.queryParameters['space_zone_id'];

            Map<String, dynamic> data = {'type': NOTIFICATION_CLAIM_PROPERTY_WITHSLUG, 'property_slug': propertySlug, 'unit_slug': unitSlug, 'space_slug': spaceSlug, 'space_zone_id': spaceZoneID};
            data.addAll(dynamicLinkData.link.queryParameters);
            await clickHandle(data);
          } else {
            final qrUri = Uri.parse(dynamicLinkData.link.toString());

            if (dynamicLinkData.link.toString().contains('is_finish')) {
              String? propertySlug = qrUri.queryParameters['property_slug'];
              String? unitSlug = qrUri.queryParameters['unit_id'];
              String? spaceZoneId = qrUri.queryParameters['space_zone_id'];
              String productCategoryHeadingId = qrUri.queryParameters['product_category_heading_id'] ?? "";
              String productCategoryHeadingName = qrUri.queryParameters['product_category_heading_name'] ?? "";
              String parentProductCategoryHeadingName = qrUri.queryParameters['parent_product_category_heading_name'] ?? "";
              String productTypeId = qrUri.queryParameters['product_type_id'] ?? "";
              String productTypeName = qrUri.queryParameters['product_type_name'] ?? "";
              String finishCategoryHeadingName = qrUri.queryParameters['finish_category_heading_name'] ?? "";
              String isFinish = qrUri.queryParameters['is_finish'] ?? "";
              String unitSpaceId = qrUri.queryParameters['unit_space_id'] ?? "";
              String unitSpaceName = qrUri.queryParameters['unit_space_name'] ?? "";
              String parentUnitSpaceName = qrUri.queryParameters['parent_unit_space_name'] ?? "";

              Map<String, dynamic> data = {
                'type': NOTIFICATION_CLAIM_PROPERTY_WITHSLUG,
                'property_slug': propertySlug,
                'unit_id': unitSlug,
                'space_zone_id': spaceZoneId,
                'product_category_heading_id': productCategoryHeadingId,
                'product_category_heading_name': productCategoryHeadingName,
                'parent_product_category_heading_name': parentProductCategoryHeadingName,
                'product_type_id': productTypeId,
                'product_type_name': productTypeName,
                'finish_category_heading_name': finishCategoryHeadingName,
                'is_finish': isFinish,
                'unit_space_id': unitSpaceId,
                'unit_space_name': unitSpaceName,
                'parent_unit_space_name': parentUnitSpaceName,
              };
              data.addAll(dynamicLinkData.link.queryParameters);
              await clickHandle(data);
            } else {
              String? propertySlug = qrUri.queryParameters['property_slug'];
              String? unitSlug = qrUri.queryParameters['unit_id'];
              String? spaceZoneId = qrUri.queryParameters['space_zone_id'];
              String? productCategoryHeadingId = qrUri.queryParameters['product_category_heading_id'];
              String? productCategoryHeadingName = qrUri.queryParameters['product_category_heading_name'];
              String parentProductCategoryHeadingName = qrUri.queryParameters['parent_product_category_heading_name'] ?? "";
              String productTypeId = qrUri.queryParameters['product_type_id'] ?? "";
              String productTypeName = qrUri.queryParameters['product_type_name'] ?? "";
              String finishCategoryHeadingName = qrUri.queryParameters['finish_category_heading_name'] ?? "";
              String unitSpaceId = qrUri.queryParameters['unit_space_id'] ?? "";
              String unitSpaceName = qrUri.queryParameters['unit_space_name'] ?? "";
              String parentUnitSpaceName = qrUri.queryParameters['parent_unit_space_name'] ?? "";

              Map<String, dynamic> data = {
                'type': NOTIFICATION_CLAIM_PROPERTY_WITHSLUG,
                'property_slug': propertySlug,
                'unit_id': unitSlug,
                'space_zone_id': spaceZoneId,
                'product_category_heading_id': productCategoryHeadingId,
                'product_category_heading_name': productCategoryHeadingName,
                'parent_product_category_heading_name': parentProductCategoryHeadingName,
                'product_type_id': productTypeId,
                'product_type_name': productTypeName,
                'finish_category_heading_name': finishCategoryHeadingName,
                'unit_space_id': unitSpaceId,
                'unit_space_name': unitSpaceName,
                'parent_unit_space_name': parentUnitSpaceName,
              };
              data.addAll(dynamicLinkData.link.queryParameters);
              await clickHandle(data);
            }
          }
        }
      }
    }).onError((error) {
      print(error.message);
    });
  }

  Future<void> dynamicLinkRedirection(Uri dynamicLinks) async {
    isFromDynamicLink = true;
    print("link launching 11 -- -- -- - ${dynamicLinks.toString()}");
    if (dynamicLinks.toString().contains('confirm-account')) {
      /// Handling confirm Account...
      /*final preference = GetIt.instance<Preferences>();
        final token = await preference.getUserToken();
        final emailVerified = await preference.getIsEmailVerified();*/

      // if (!token.isNullOrEmpty()) {
      // if (!(emailVerified ?? false)) {
      Map<String, dynamic> data = {'type': NOTIFICATION_VERIFY_THIS_EMAIL};
      data.addAll(dynamicLinks.queryParameters);
      clickHandle(data);
      // App.navigatorKey.currentState!.pushNamed(EmailVerificationScreen.route);
      // }
      // }
    } else if (dynamicLinks.toString().contains('reset-password')) {
      /// Handling reset password...

      Map<String, dynamic> data = {'type': NOTIFICATION_RESET_PASSWORD};

      data.addAll(dynamicLinks.queryParameters);

      clickHandle(data);
    } else if (dynamicLinks.toString().contains('claim-your-homeguide')) {
      /// Claim Your Homeguide...

      if (dynamicLinks.toString().contains('claim-your-homeguide?property_slug')) {
        propertySlug = dynamicLinks.queryParameters['property_slug'];
        Map<String, dynamic> data = {'type': NOTIFICATION_CLAIM_PROPERTY};
        data.addAll(dynamicLinks.queryParameters);
        clickHandle(data);
      } else {
        propertySlug = "";
        Map<String, dynamic> data = {'type': NOTIFICATION_CLAIM_PROPERTY};
        data.addAll(dynamicLinks.queryParameters);
        clickHandle(data);
      }
    } else if (dynamicLinks.toString().contains('workarea')) {
      /// Claim Your Homeguide with slug...
      ///
      propertyHomeGuideSlug = dynamicLinks.toString().split('workarea/')[1].split('/virtualhome')[0];
      if (dynamicLinks.toString().contains('workarea/$propertyHomeGuideSlug/homeguide')) {
        Map<String, dynamic> data = {'type': NOTIFICATION_CLAIM_PROPERTY_WITHSLUG};
        data.addAll(dynamicLinks.queryParameters);
        await clickHandleKill(data);
      } else {
        if (dynamicLinks.toString().contains('space_slug') == true) {
          final qrUri = Uri.parse(dynamicLinks.toString());
          String? propertySlug = qrUri.queryParameters['property_slug'];
          String? unitSlug = qrUri.queryParameters['unit_slug'];
          String? spaceSlug = qrUri.queryParameters['space_slug'];
          String? spaceZoneID = qrUri.queryParameters['space_zone_id'];

          Map<String, dynamic> data = {'type': NOTIFICATION_CLAIM_PROPERTY_WITHSLUG, 'property_slug': propertySlug, 'unit_slug': unitSlug, 'space_slug': spaceSlug, 'space_zone_id': spaceZoneID};
          data.addAll(dynamicLinks.queryParameters);
          await clickHandleKill(data);
        } else {
          final qrUri = Uri.parse(dynamicLinks.toString());

          if (dynamicLinks.toString().contains('is_finish')) {
            String? propertySlug = qrUri.queryParameters['property_slug'];
            String? unitSlug = qrUri.queryParameters['unit_id'];
            String? spaceZoneId = qrUri.queryParameters['space_zone_id'];
            String productCategoryHeadingId = qrUri.queryParameters['product_category_heading_id'] ?? "";
            String productCategoryHeadingName = qrUri.queryParameters['product_category_heading_name'] ?? "";
            String parentProductCategoryHeadingName = qrUri.queryParameters['parent_product_category_heading_name'] ?? "";
            String productTypeId = qrUri.queryParameters['product_type_id'] ?? "";
            String productTypeName = qrUri.queryParameters['product_type_name'] ?? "";
            String finishCategoryHeadingName = qrUri.queryParameters['finish_category_heading_name'] ?? "";
            String isFinish = qrUri.queryParameters['is_finish'] ?? "";
            String unitSpaceId = qrUri.queryParameters['unit_space_id'] ?? "";
            String unitSpaceName = qrUri.queryParameters['unit_space_name'] ?? "";
            String parentUnitSpaceName = qrUri.queryParameters['parent_unit_space_name'] ?? "";

            Map<String, dynamic> data = {
              'type': NOTIFICATION_CLAIM_PROPERTY_WITHSLUG,
              'property_slug': propertySlug,
              'unit_id': unitSlug,
              'space_zone_id': spaceZoneId,
              'product_category_heading_id': productCategoryHeadingId,
              'product_category_heading_name': productCategoryHeadingName,
              'parent_product_category_heading_name': parentProductCategoryHeadingName,
              'product_type_id': productTypeId,
              'product_type_name': productTypeName,
              'finish_category_heading_name': finishCategoryHeadingName,
              'is_finish': isFinish,
              'unit_space_id': unitSpaceId,
              'unit_space_name': unitSpaceName,
              'parent_unit_space_name': parentUnitSpaceName,
            };
            data.addAll(dynamicLinks.queryParameters);
            await clickHandleKill(data);
          } else {
            String? propertySlug = qrUri.queryParameters['property_slug'];
            String? unitSlug = qrUri.queryParameters['unit_id'];
            String? spaceZoneId = qrUri.queryParameters['space_zone_id'];
            String? productCategoryHeadingId = qrUri.queryParameters['product_category_heading_id'];
            String? productCategoryHeadingName = qrUri.queryParameters['product_category_heading_name'];
            String parentProductCategoryHeadingName = qrUri.queryParameters['parent_product_category_heading_name'] ?? "";
            String productTypeId = qrUri.queryParameters['product_type_id'] ?? "";
            String productTypeName = qrUri.queryParameters['product_type_name'] ?? "";
            String finishCategoryHeadingName = qrUri.queryParameters['finish_category_heading_name'] ?? "";
            String unitSpaceId = qrUri.queryParameters['unit_space_id'] ?? "";
            String unitSpaceName = qrUri.queryParameters['unit_space_name'] ?? "";
            String parentUnitSpaceName = qrUri.queryParameters['parent_unit_space_name'] ?? "";

            Map<String, dynamic> data = {
              'type': NOTIFICATION_CLAIM_PROPERTY_WITHSLUG,
              'property_slug': propertySlug,
              'unit_id': unitSlug,
              'space_zone_id': spaceZoneId,
              'product_category_heading_id': productCategoryHeadingId,
              'product_category_heading_name': productCategoryHeadingName,
              'parent_product_category_heading_name': parentProductCategoryHeadingName,
              'product_type_id': productTypeId,
              'product_type_name': productTypeName,
              'finish_category_heading_name': finishCategoryHeadingName,
              'unit_space_id': unitSpaceId,
              'unit_space_name': unitSpaceName,
              'parent_unit_space_name': parentUnitSpaceName,
            };
            data.addAll(dynamicLinks.queryParameters);
            await clickHandleKill(data);
          }
        }
      }
    }
  }
}
Editor is loading...
Leave a Comment