import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:logger/logger.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/consts.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/generated/codegen_loader.g.dart';
import 'package:mohem_flutter_app/models/post_params_model.dart';
import 'package:mohem_flutter_app/provider/chat_provider_model.dart';
import 'package:mohem_flutter_app/provider/dashboard_provider_model.dart';
import 'package:mohem_flutter_app/provider/eit_provider_model.dart';
import 'package:mohem_flutter_app/theme/app_theme.dart';
import 'package:mohem_flutter_app/ui/marathon/marathon_provider.dart';
import 'package:month_year_picker/month_year_picker.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
import 'package:sizer/sizer.dart';

Logger logger = Logger(
  // filter: null, // Use the default LogFilter (-> only log in debug mode)
  printer: PrettyPrinter(
    lineLength: 0,
  ), // Use the PrettyPrinter to format and print log
  // output: null, // U
);

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

bool isTablet = false;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  await EasyLocalization.ensureInitialized();
  AppState().setPostParamsInitConfig();
  HttpOverrides.global = MyHttpOverrides();
  isTablet = MediaQueryData.fromWindow(WidgetsBinding.instance.window).size.shortestSide >= ApiConsts.tabletMinLength;

  runApp(
    EasyLocalization(
      supportedLocales: const <Locale>[
        Locale('en', 'US'),
        Locale('ar', 'SA'),
      ],
      path: 'assets/langs',
      assetLoader: const CodegenLoader(),
      child: MultiProvider(
        providers: <SingleChildWidget>[
          ChangeNotifierProvider<DashboardProviderModel>(
            create: (_) => DashboardProviderModel(),
          ),
          ChangeNotifierProvider<EITProviderModel>(
            create: (_) => EITProviderModel(),
          ),
          ChangeNotifierProvider<ChatProviderModel>(
            create: (_) => ChatProviderModel(),
          ),
          ChangeNotifierProvider<MarathonProvider>(
            create: (_) => MarathonProvider(),
          )
        ],
        child: const MyApp(),
      ),
    ),
  );
}

// todo terminal command to generate translation files
// flutter pub run easy_localization:generate --source-dir ./assets/langs
// todo terminal command to generate translation keys
// flutter pub run easy_localization:generate --source-dir ./assets/langs -f keys -o locale_keys.g.dart
// command to generate languages data from json

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

  @override
  Widget build(BuildContext context) {
    return Sizer(
      builder: (
        BuildContext context,
        Orientation orientation,
        DeviceType deviceType,
      ) {
        PostParamsModel? obj = AppState().postParamsObject;
        obj?.languageID = EasyLocalization.of(context)?.locale.languageCode == "ar" ? 1 : 2;
        AppState().setPostParamsModel(obj!);
        List<LocalizationsDelegate<dynamic>> delegates = context.localizationDelegates;
        // delegates.add(GlobalMaterialLocalizations.delegate);
        delegates.add(
          MonthYearPickerLocalizations.delegate,
        );
        return MaterialApp(
          navigatorKey: AppRoutes.navigatorKey,
          builder: (BuildContext context, Widget? child) {
            return MediaQuery(
              data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
              child: child!,
            );
          },
          theme: AppTheme.getTheme(
            EasyLocalization.of(context)?.locale.languageCode == "ar",
          ),
          debugShowCheckedModeBanner: false,
          localizationsDelegates: delegates,
          supportedLocales: context.supportedLocales,
          locale: context.locale,
          initialRoute: AppRoutes.initialRoute,
          routes: AppRoutes.routes,
        );
      },
    );
  }
}

// class MyApp extends StatefulWidget {
//   @override
//   State<StatefulWidget> createState() => MyAppState();
// }
//
// class MyAppState extends State<MyApp> {
//   ValueNotifier<dynamic> result = ValueNotifier(null);
//
//   @override
//   Widget build(BuildContext context) {
//     return MaterialApp(
//       home: Scaffold(
//         appBar: AppBar(title: Text('NfcManager Plugin Example')),
//         body: SafeArea(
//           child: FutureBuilder<bool>(
//             future: NfcManager.instance.isAvailable(),
//             builder: (context, ss) => ss.data != true
//                 ? Center(child: Text('NfcManager.isAvailable(): ${ss.data}'))
//                 : Flex(
//                     mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                     direction: Axis.vertical,
//                     children: [
//                       Flexible(
//                         flex: 2,
//                         child: Container(
//                           margin: EdgeInsets.all(4),
//                           constraints: BoxConstraints.expand(),
//                           decoration: BoxDecoration(border: Border.all()),
//                           child: SingleChildScrollView(
//                             child: ValueListenableBuilder<dynamic>(
//                               valueListenable: result,
//                               builder: (context, value, _) => Text('${value ?? ''}'),
//                             ),
//                           ),
//                         ),
//                       ),
//                       Flexible(
//                         flex: 3,
//                         child: GridView.count(
//                           padding: EdgeInsets.all(4),
//                           crossAxisCount: 2,
//                           childAspectRatio: 4,
//                           crossAxisSpacing: 4,
//                           mainAxisSpacing: 4,
//                           children: [
//                             ElevatedButton(child: Text('Tag Read'), onPressed: _tagRead),
//                             ElevatedButton(child: Text('Ndef Write'), onPressed: _ndefWrite),
//                             ElevatedButton(child: Text('Ndef Write Lock'), onPressed: _ndefWriteLock),
//                           ],
//                         ),
//                       ),
//                     ],
//                   ),
//           ),
//         ),
//       ),
//     );
//   }
//
//   void _tagRead() {
//     showNfcReader(
//       context,
//       onNcfScan: (String? nfcId) {},
//     );
//     // NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
//     //   result.value = tag.data;
//     //   print(tag.data);
//     //   var ndef = Ndef.from(tag);
//     //
//     //   var f = MifareUltralight(tag: tag, identifier: tag.data["nfca"]["identifier"], type: 2, maxTransceiveLength: 252, timeout: 22);
//     //   final String identifier = f.identifier.map((e) => e.toRadixString(16).padLeft(2, '0')).join('');
//     //   print(identifier); // => 0428fcf2255e81
//     //   print(ndef!.additionalData);
//     //
//     //   // onDiscovered callback
//     //   // final mifare = MiFare.from(tag);
//     //   // if (mifare == null) {
//     //   //   print('Tag is not compatible with MiFare.');
//     //   //   return;
//     //   // }
//     //   // print(mifare.identifier);
//     //   // final String identifier = mifare.identifier.map((e) => e.toRadixString(16).padLeft(2, '0')).join('');
//     //   // print(identifier); // => 0428fcf2255e81
//     //   NfcManager.instance.stopSession();
//     // });
//   }
//
//   void _ndefWrite() {
//     NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
//       var ndef = Ndef.from(tag);
//       if (ndef == null || !ndef.isWritable) {
//         result.value = 'Tag is not ndef writable';
//         NfcManager.instance.stopSession(errorMessage: result.value);
//         return;
//       }
//
//       NdefMessage message = NdefMessage([
//         NdefRecord.createText('Hello World!'),
//         NdefRecord.createUri(Uri.parse('https://flutter.dev')),
//         NdefRecord.createMime('text/plain', Uint8List.fromList('Hello'.codeUnits)),
//         NdefRecord.createExternal('com.example', 'mytype', Uint8List.fromList('mydata'.codeUnits)),
//       ]);
//
//       try {
//         await ndef.write(message);
//         result.value = 'Success to "Ndef Write"';
//         NfcManager.instance.stopSession();
//       } catch (e) {
//         result.value = e;
//         NfcManager.instance.stopSession(errorMessage: result.value.toString());
//         return;
//       }
//     });
//   }
//
//   void _ndefWriteLock() {
//     NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
//       var ndef = Ndef.from(tag);
//       if (ndef == null) {
//         result.value = 'Tag is not ndef';
//         NfcManager.instance.stopSession(errorMessage: result.value.toString());
//         return;
//       }
//
//       try {
//         await ndef.writeLock();
//         result.value = 'Success to "Ndef Write Lock"';
//         NfcManager.instance.stopSession();
//       } catch (e) {
//         result.value = e;
//         NfcManager.instance.stopSession(errorMessage: result.value.toString());
//         return;
//       }
//     });
//   }
// }

