import 'dart:convert';
import 'dart:io';

import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:naim/classes/appdata.dart';
import 'package:naim/classes/assets.dart';
import 'package:naim/classes/cipher.dart';
import 'package:naim/packages/custom_splash.dart';
import 'package:naim/screens/auth/pass.dart';
import 'package:naim/screens/home.dart';
import 'package:naim/screens/onboarding.dart';
import 'package:naim/screens/profile_settings.dart';

import 'classes/Authenticate.dart';

final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

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();
  print('Handling a background message ${message.messageId}');

  var msg = json.decode(message.data["details"]);
  if (msg["type"] == "new_message") {
    if (Platform.isAndroid) {
      FirebaseMessaging.onBackgroundMessage(
          _firebaseMessagingBackgroundHandler);

      await flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              AndroidFlutterLocalNotificationsPlugin>()
          ?.createNotificationChannel(channel);

      /// Update the iOS foreground notification presentation options to allow
      /// heads up notifications.
      await FirebaseMessaging.instance
          .requestPermission(alert: true, badge: true, sound: true);
      await FirebaseMessaging.instance
          .setForegroundNotificationPresentationOptions(
        alert: true,
        badge: true,
        sound: true,
      );

      run();
    }
  }
}

const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel', // id
  'High Importance Notifications', // title
  description:
      'This channel is used for important notifications.', // description
  importance: Importance.high,
);

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  await Hive.openBox<dynamic>('naim');

  await Firebase.initializeApp();
  if (Platform.isAndroid) {
    // await CallKeep.setup();
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  }

  await FirebaseMessaging.instance
      .requestPermission(alert: true, badge: true, sound: true);
  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );
  run();
}

Future run() async {
  print(decryptIt("ywmiAWCDiHTv5TUw2zf/fA==", "241100"));
  runApp(const MyApp());
}

// ignore: prefer_function_declarations_over_variables
Function duringSplash = () async {
  await Firebase.initializeApp();
  GUser nuser = GUser();
  await nuser.getCurrentUser();
  //print("=========!" + appData.dbUser["username"] + "!==========");
  if (appData.dbUser["id"] != null) {
    if (appData.dbUser["username"] != "") {
      return 1;
    } else {
      return 2;
    }
  } else {
    return 0;
  }
};

Map<int, Widget> op = {
  0: Onboarding(),
  1: UnlockPage(true),
  2: ProfileSettings(true)
};

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);

    return GestureDetector(
        onTap: () {
          FocusScopeNode currentFocus = FocusScope.of(context);
          if (!currentFocus.hasPrimaryFocus) {
            currentFocus.unfocus();
          }
        },
        child: MaterialApp(
            title: 'Nigeria Army Instant Messenger',
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
                fontFamily: 'Montserrat',
                outlinedButtonTheme: OutlinedButtonThemeData(
                    style: OutlinedButton.styleFrom(primary: armyGreen))),
            home: CustomSplash(
              imagePath: appLogo,
              backGroundColor: Colors.white,
              // backGroundColor: Color(0xfffc6042),
              animationEffect: 'fade-in',
              logoSize: 200,
              home: Onboarding(),
              customFunction: duringSplash,
              duration: 6500,
              type: CustomSplashType.BackgroundProcess,
              outputAndHome: op,
            )));
  }
}
