import 'dart:convert'; import 'dart:io'; import 'dart:async'; import 'package:device_calendar/device_calendar.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_timezone/flutter_timezone.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:google_api_availability/google_api_availability.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/controllers/notification/notification_manger.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart'; import 'package:test_sa/service_request_latest/service_request_detail_provider.dart'; import 'package:huawei_push/huawei_push.dart' as h_push; class ServiceRequestUtils { static double calculateAndAssignWorkingHours({ required DateTime? startTime, required DateTime? endTime, required TextEditingController workingHoursController, required Function(double) updateModel, // A callback to update the model }) { if (startTime != null && endTime != null) { Duration difference = endTime.difference(startTime); double hours = difference.inMinutes / 60.0; // Calculate hours as a decimal workingHoursController.text = hours.toStringAsFixed(1); // Format to 1 decimal places updateModel(hours); // Call the function to update the model return hours; } else { return -1; // Indicating invalid input } } static String calculateTimeDifference(DateTime startDate, DateTime endDate) { try { Duration diff = startDate.difference(endDate); int days = diff.inDays; int hours = diff.inHours.remainder(24); int minutes = diff.inMinutes.remainder(60); int seconds = diff.inSeconds.remainder(60); List parts = []; if (days > 0) parts.add('$days ${days == 1 ? 'day' : 'days'}'); if (hours > 0) parts.add('$hours ${hours == 1 ? 'hour' : 'hours'}'); if (minutes > 0) parts.add('$minutes ${minutes == 1 ? 'minute' : 'minutes'}'); if (seconds > 0) parts.add('$seconds ${seconds == 1 ? 'second' : 'seconds'}'); String timeDifference = parts.isEmpty ? '' : parts.join(', '); return 'Action duration: $timeDifference'; } catch (e) { return ''; } } static void getQrCode({required BuildContext context }) async{ showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); ServiceRequestDetailProvider requestDetailProvider = Provider.of(context,listen:false); String? base64String = await requestDetailProvider.getQrCode(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId ?? 0); Navigator.pop(context); if (base64String != null) { // You have the base64 string, now you can display it Uint8List bytes = base64Decode(base64String); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( backgroundColor: Colors.white, title:context.translation.scanQr.heading6(context).center, content: Image.memory( bytes, // Displaying the QR code from base64 fit: BoxFit.contain, // Ensure the image fits well in the dialog errorBuilder: (context, error, stackTrace) { return const Icon(Icons.error, color: Colors.red); }, ), ); }, ); } else { print('Failed to get the QR code'); } } static Widget testScheduleNotificationButton({required BuildContext context}){ return ElevatedButton( child: const Text('Schedule notifications'), onPressed: () { // debugPrint('Notification Scheduled for $D'); // NotificationManger.showNotification(context: context, title: 'test notification', subtext: 'test notification', hashcode: 1); DateTime scheduleTime= DateTime.now().add(const Duration(seconds: 10)); NotificationManger.scheduleNotification( title: 'Scheduled Notification', body: '$scheduleTime', scheduledNotificationDateTime: scheduleTime);(); }, ); } //steps: //add permission for andriod.. //add string in info.plist for ios... //create event.. static Widget testAddEventToCalendarButton({required BuildContext context}){ return ElevatedButton( child: const Text('Add Event to Calendar'), onPressed: () async { var currentLocation = getLocation( await FlutterTimezone.getLocalTimezone()); setLocalLocation(currentLocation); await Future.delayed(const Duration(seconds: 2)); var eventToCreate = Event( "1", title: "test123", description: "test", start: TZDateTime.now(currentLocation), end: TZDateTime.now(currentLocation).add(const Duration(seconds: 10)), ); final createEventResult = await DeviceCalendarPlugin().createOrUpdateEvent(eventToCreate); if (createEventResult!.isSuccess) { Fluttertoast.showToast(msg: 'added successfully'); } }, ); } // Map messageData = message.data; // if (messageData["notificationType"] != null && messageData["accept"] != null) { // if (messageData["notificationType"] == "arrivalConfirmation") { // if ((messageData["accept"].toString()) == "False") { // if(messageData["accept"]) // Navigator.pop(context, true); // } else { // Navigator.pop(context, false); // } // } // } static Future listenForApproval() async { print('listen for approval called..'); bool isVerified = false; Completer completer = Completer(); if (Platform.isAndroid && !(await isGoogleServicesAvailable())) { // If not using Firebase (i.e., if Google Services is unavailable) h_push.Push.onMessageReceivedStream.listen((h_push.RemoteMessage remoteMessage) { ConfirmArrivalNotificationModel notificationModel = ConfirmArrivalNotificationModel.fromJson(remoteMessage.toMap()); if (notificationModel.requestId != null && notificationModel.accept != null) { if (notificationModel.accept == 'True') { isVerified = true; completer.complete(isVerified); } else if (notificationModel.accept == 'False') { isVerified = false; completer.complete(isVerified); } } }, onError: (Object error) { print("onMessageReceivedStream:${error.toString()}"); completer.complete(false); // Handle any error }); } else { // Using Firebase FirebaseMessaging.onMessage.listen((RemoteMessage message) { print('message data received: ${message.data}'); ConfirmArrivalNotificationModel notificationModel = ConfirmArrivalNotificationModel.fromJson(message.data); if (notificationModel.requestId != null && notificationModel.accept != null) { if (notificationModel.accept == 'True') { isVerified = true; if (!completer.isCompleted) { completer.complete(isVerified); } } else if (notificationModel.accept == 'False') { isVerified = false; if (!completer.isCompleted) { completer.complete(isVerified); } } } }); } // Wait for the future to complete with the notification response return completer.future; } static Future isGoogleServicesAvailable() async { GooglePlayServicesAvailability availability = await GoogleApiAvailability.instance.checkGooglePlayServicesAvailability(); String status = availability.toString().split('.').last; if (status == "success") { return true; } return false; } } class ConfirmArrivalNotificationModel { final String? transactionType; final String? requestId; final String? notificationType; final String? userId; final String? accept; ConfirmArrivalNotificationModel({ this.transactionType, this.requestId, this.notificationType, this.userId, this.accept, }); // Factory constructor to create an instance from a Map (e.g., JSON) factory ConfirmArrivalNotificationModel.fromJson(Map json) { return ConfirmArrivalNotificationModel( transactionType: json['transactionType'], requestId: json['requestId'], notificationType: json['notificationType'], userId: json['userId'], accept: json['accept'], ); } // Convert an instance to a Map (e.g., for serialization) Map toJson() { return { 'transactionType': transactionType, 'requestId': requestId, 'notificationType': notificationType, 'userId': userId, 'accept': accept, }; } }