import 'dart:io';

import 'package:diplomaticquarterapp/core/viewModels/PharmacyPagesViewModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/dashboard_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/robo_search/event_provider.dart';
import 'package:diplomaticquarterapp/services/robo_search/search_provider.dart';
import 'package:diplomaticquarterapp/theme/theme_notifier.dart';
import 'package:diplomaticquarterapp/theme/theme_value.dart';
import 'package:diplomaticquarterapp/uitl/LocalNotification.dart';
import 'package:diplomaticquarterapp/uitl/PlatformBridge.dart';
import 'package:diplomaticquarterapp/uitl/navigation_service.dart';
import 'package:diplomaticquarterapp/uitl/push-notification-handler.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
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_localizations/flutter_localizations.dart';
import 'package:in_app_update/in_app_update.dart';
import 'package:provider/provider.dart';

import 'config/size_config.dart';
import 'core/viewModels/pharmacyModule/OrderPreviewViewModel.dart';
import 'core/viewModels/project_view_model.dart';
import 'locator.dart';
import 'pages/pharmacies/compare-list.dart';




void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  setupLocator();
  HttpOverrides.global = MyHttpOverrides();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyApp createState() => new _MyApp();
}

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


class _MyApp extends State<MyApp> {
  AppUpdateInfo _updateInfo;

  final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  Future<void> checkForUpdate() async  { // todo need to verify 'imp'
    InAppUpdate.checkForUpdate().then((info) {
      if (info.immediateUpdateAllowed) {
        InAppUpdate.performImmediateUpdate().then((value) {}).catchError((e) => print(e.toString()));
      }
    }).catchError((e) {
      print(e.toString());
    });
  }

  @override
  void initState() {
    // ProjectViewModel projectProvider;
    // projectProvider = Provider.of(context);
    // var font = projectProvider.isArabic ? 'Cairo' : 'WorkSans';

    // Re-enable once going live
    // if (Platform.isAndroid) checkForUpdate();

    ThemeNotifier(defaultTheme());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    PlatformBridge.init(context);
    PushNotificationHandler(context).init(); // Asyncronously

    LocalNotification.init(onNotificationClick: (payload) {
      LocalNotification.getInstance().showNow(title: "Payload", subtitle: payload, payload: payload);
    });

    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.portraitUp,
    //   DeviceOrientation.portraitDown,
    // ]);
    // final themeNotifier = Provider.of<ThemeNotifier>(context);
    precacheImage(AssetImage('assets/images/powerd-by.jpg'), context);
    return LayoutBuilder(
      builder: (context, constraints) {
        return OrientationBuilder(
          builder: (context, orientation) {
            SizeConfig().init(constraints, orientation);
            return MultiProvider(
              providers: [
                ChangeNotifierProvider<PharmacyPagesViewModel>(
                  create: (context) => PharmacyPagesViewModel(),
                ),
                ChangeNotifierProvider<ProjectViewModel>(
                  create: (context) => ProjectViewModel(),
                ),
                ChangeNotifierProvider<DashboardViewModel>(
                  create: (context) => DashboardViewModel(),
                ),
                ChangeNotifierProvider<ToDoCountProviderModel>(create: (context) => ToDoCountProviderModel()),
                ChangeNotifierProvider<SearchProvider>(create: (context) => SearchProvider()),
                ChangeNotifierProvider.value(
                  value: SearchProvider(),
                ),
                ChangeNotifierProvider<ThemeNotifier>(create: (context) => ThemeNotifier(defaultTheme())),
                StreamProvider.value(
                  value: RobotProvider().intStream(),
                  initialData: RobotProvider().setValue({}),
                ),
                ChangeNotifierProvider<CompareList>(create: (context) => CompareList()),
                ChangeNotifierProvider<OrderPreviewViewModel>(create: (context) => OrderPreviewViewModel()),
              ],
              child: Consumer<ProjectViewModel>(
                builder: (context, projectProvider, child) => MaterialApp(
                  // navigatorObservers: [
                  //   GAnalytics.shared.navObserver()
                  // ],
                  navigatorKey: locator<NavigationService>().navigatorKey,
                  showSemanticsDebugger: false,
                  title: 'Dr. AlHabib',
                  locale: projectProvider.appLocal,
                  localizationsDelegates: [
                    TranslationBaseDelegate(),
                    GlobalMaterialLocalizations.delegate,
                    GlobalWidgetsLocalizations.delegate,
                    GlobalCupertinoLocalizations.delegate,
                  ],
                  supportedLocales: [
                    const Locale('ar', ''), // Arabic
                    const Locale('en', ''), // English
                  ],
                  theme: Provider.of<ThemeNotifier>(context).getTheme(),
                  // theme: ThemeData(
                  //   fontFamily: projectProvider.isArabic ? 'Cairo' : 'WorkSans',
                  //   primarySwatch: Colors.blue,
                  //   visualDensity: VisualDensity.adaptivePlatformDensity,
                  //   brightness: Brightness.light,
                  //   pageTransitionsTheme: const PageTransitionsTheme(
                  //     builders: {
                  //       TargetPlatform.android: ZoomPageTransitionsBuilder(),
                  //       TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
                  //     },
                  //   ),
                  //   hintColor: Colors.grey[400],
                  //   textTheme: TextTheme(
                  //     headline1: TextStyle(
                  //       color: Color(0xffB8382C),
                  //     ),
                  //   ),
                  //   disabledColor: Colors.grey[300],
                  //   errorColor: Color.fromRGBO(235, 80, 60, 1.0),
                  //   scaffoldBackgroundColor:
                  //       Color(0xffE9E9E9), // Colors.grey[100],
                  //   textSelectionColor: Color.fromRGBO(80, 100, 253, 0.5),
                  //   textSelectionHandleColor: Colors.grey,
                  //   canvasColor: Colors.white,
                  //   backgroundColor: Color.fromRGBO(255, 255, 255, 1),
                  //   highlightColor: Colors.grey[100].withOpacity(0.4),
                  //   splashColor: Colors.transparent,
                  //   primaryColor: Color(0xff515A5D),
                  //   toggleableActiveColor: secondaryColor,
                  //   indicatorColor: secondaryColor,
                  //   bottomSheetTheme: BottomSheetThemeData(
                  //       backgroundColor: HexColor('#E0E0E0')),
                  //   cursorColor: Colors.grey,
                  //   iconTheme: IconThemeData(),
                  //   appBarTheme: AppBarTheme(
                  //     color: Color(0xff515A5D),
                  //     brightness: Brightness.light,
                  //     elevation: 0.0,
                  //     actionsIconTheme: IconThemeData(
                  //       color: Colors.grey[800],
                  //     ),
                  //   ),
                  // ),
                  initialRoute: SPLASH,
                  // initialRoute: CALL_PAGE,
                  // initialRoute: OPENTOK_CALL_PAGE,
                  // initialRoute: PACKAGES_OFFERS,
                  // initialRoute: PACKAGES_ORDER_COMPLETED,
                  routes: routes,
                  debugShowCheckedModeBanner: false,
                ),
              ),
            );
          },
        );
      },
    );
  }
}
