//general
import 'dart:io';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:aman_kassa_flutter/shared/app_colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

//service & tools
import 'package:aman_kassa_flutter/redux/store.dart';
import 'core/locator.dart';
import 'core/router.dart';
import 'core/services/navigator_service.dart';
import 'core/services/dialog_service.dart';
import './widgets/dialog_manager.dart';

//pages
import 'views/start_up/start_up_view.dart';

//main start
void main() async {
  // HttpOverrides.global = MyHttpOverrides();




  WidgetsFlutterBinding.ensureInitialized();
  HttpOverrides.global = MyHttpOverrides();
  //initialize locator
  await LocatorInjector.setupLocator();

  LicenseRegistry.addLicense(() async* {
    final license = await rootBundle.loadString('assets/google_fonts/OFL.txt');
    yield LicenseEntryWithLineBreaks(['google_fonts'], license);
  });

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );


  FirebaseMessaging messaging = FirebaseMessaging.instance;

  NotificationSettings settings = await messaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  print('User granted permission: ${settings.authorizationStatus}');

  await FirebaseMessaging.instance.subscribeToTopic('all');
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    if (message.notification != null) {
      locator<DialogService>().showDialog(description: message.notification?.body ?? '');
    }
  });

  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
    if (message.notification != null) {
      locator<DialogService>().showDialog(description: message.notification?.body ?? '');
    }
  });


  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  await Redux.init();
  runApp(MainApplication());
}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp();
}

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
  }
}

class MainApplication extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return StoreProvider<AppState>(
        store: Redux.store!,
        child: ScreenUtilInit(
          designSize: const Size(
            411.43,
            683.43,
          ),
          builder: (context, child) => MaterialApp(
            theme: ThemeData(
              colorScheme: ColorScheme.fromSeed(seedColor: primaryColor).copyWith(surface: backgroundColor),
              primaryColor: primaryColor,
              scaffoldBackgroundColor: Colors.white,
              // textTheme: GoogleFonts.latoTextTheme(
              //   Theme.of(context).textTheme,
              // )
            ),
            debugShowCheckedModeBanner: false,
            builder: (context, child) => Navigator(
              key: locator<DialogService>().dialogNavigationKey,
              onGenerateRoute: (settings) => MaterialPageRoute(
                  builder: (context) => DialogManager(child: child)),
            ),
            navigatorKey: locator<NavigatorService>().navigatorKey,
            home: StartUpView(),
            // first page
            onGenerateRoute: generateRoute,
          ),
        ));
  }
}
