// ignore_for_file: prefer_const_constructors

import 'dart:ui';
//import 'dart:developer' as developer;
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

import 'package:path_provider/path_provider.dart';

import 'objectbox.dart';
import 'package:wakelock/wakelock.dart';

import 'package:event_bus_plus/event_bus_plus.dart';

import 'package:mobdr/config/constant.dart';

import 'package:mobdr/cubit/language/language_cubit.dart';
import 'package:mobdr/cubit/language/app_localizations.dart';
import 'package:mobdr/cubit/language/initial_language.dart';
import 'package:mobdr/service/shared_prefs.dart';
import 'package:mobdr/ui/splash_screen.dart';

/// Provides access to the ObjectBox Store throughout the app.
late ObjectBox objectbox;

final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();

final EventBus eventBus = EventBus();

Future<void> main() async {
  // This is required so ObjectBox can get the application directory
  // to store the database in.
  WidgetsFlutterBinding.ensureInitialized();

  await SharedPrefs().init();

  objectbox = await ObjectBox.create();

  /// Log
  objectbox.addLog('LOG', 'MOBDR', 'Ouverture application ', 0);

  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    /// pour wakelock
    WidgetsFlutterBinding.ensureInitialized();
    Wakelock.enable();

    eventBus.on().listen((event) {
      print('${DateTime.now()} Event: $event');
    });

    runApp(MyApp());
  });
}

class MyCustomScrollBehavior extends MaterialScrollBehavior {
  // Override behavior methods and getters like dragDevices
  @override
  Set<PointerDeviceKind> get dragDevices => {
        PointerDeviceKind.touch,
        PointerDeviceKind.mouse,
        // etc.
      };
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    initDirectories();
    initPlatformState();

    // url MP4
    SharedPrefs().urlMP4 =
        'https://mp4.ikksgroup.com/MobilePortal4/index.html#ajax/dashboard.html';

    // Initialize all bloc provider used on this entire application here
    return MultiBlocProvider(
      providers: [
        // this bloc used for feature - change language
        BlocProvider<LanguageCubit>(
          create: (BuildContext context) => LanguageCubit(),
        ),
      ],
      // if you want to change default language, go to lib/ui/feature/multi_language/initial_language.dart and change en US to your default language
      child: InitialLanguage(
        child: BlocBuilder<LanguageCubit, LanguageState>(
            builder: (context, state) {
          return MaterialApp(
            scrollBehavior: MyCustomScrollBehavior(),
            title: APP_NAME,
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              visualDensity: VisualDensity.adaptivePlatformDensity,
              pageTransitionsTheme: PageTransitionsTheme(builders: {
                /*
                  Below is the example to change MaterialPageRoute default transition in iOS and Android :
                   FadeUpwardsPageTransitionsBuilder() <= Default MaterialPageRoute Transition
                   OpenUpwardsPageTransitionsBuilder()
                   ZoomPageTransitionsBuilder()
                   CupertinoPageTransitionsBuilder()
                  */
                TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
                TargetPlatform.android: ZoomPageTransitionsBuilder(),
              }),
            ),
            // below is used for language feature
            supportedLocales: [
              Locale('fr', 'FR'),
              Locale('en', 'US'),
              Locale('id', 'ID'),
              Locale('ar', 'DZ'),
              Locale('zh', 'HK'),
              Locale('hi', 'IN'),
              Locale('th', 'TH'),
              Locale('tk', 'TK'),
            ],
            // These delegates make sure that the localization data for the proper language is loaded
            localizationsDelegates: [
              AppLocalizationsDelegate(),
              GlobalMaterialLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate
            ],
            // Returns a locale which will be used by the app
            locale: (state is ChangeLanguageSuccess)
                ? state.locale
                : Locale('fr', 'FR'),
            home: SplashScreenPage(),
          );
        }),
      ),
    );
  }

  void initDirectories() async {
    // Get the application's document directory
    final Directory documentsDir = await getApplicationDocumentsDirectory();

    // Create a Directory object for the "photos" directory in the documents directory
    final Directory photosDir = Directory('${documentsDir.path}/photos');

    // Check if the "photos" directory exists
    if (await photosDir.exists()) {
      print(
          'The "photos" directory already exists in the documents directory.');
    } else {
      // Create the "photos" directory if it does not exist
      await photosDir.create();
      print(
          'The "photos" directory has been created in the documents directory.');
    }

    // save directories into shared Prefs
    SharedPrefs().documentsDir = documentsDir.path;
    SharedPrefs().photosDir = photosDir.path;

    // Get a list of all files in the "photos" directory
    final List<FileSystemEntity> files = await photosDir.list().toList();

    // Print out the names of the files in the directory
    for (FileSystemEntity file in files) {
      print('File name: ${file.path.split('/').last}');
    }
  }

  Future<void> initPlatformState() async {
    var deviceData = <String, dynamic>{};

    try {
      if (kIsWeb) {
        deviceData = _readWebBrowserInfo(await deviceInfoPlugin.webBrowserInfo);
      } else {
        if (Platform.isAndroid) {
          deviceData =
              _readAndroidBuildData(await deviceInfoPlugin.androidInfo);
        } else if (Platform.isIOS) {
          deviceData = _readIosDeviceInfo(await deviceInfoPlugin.iosInfo);
        } else if (Platform.isLinux) {
          deviceData = _readLinuxDeviceInfo(await deviceInfoPlugin.linuxInfo);
        } else if (Platform.isMacOS) {
          deviceData = _readMacOsDeviceInfo(await deviceInfoPlugin.macOsInfo);
        } else if (Platform.isWindows) {
          deviceData =
              _readWindowsDeviceInfo(await deviceInfoPlugin.windowsInfo);
        }
      }

      // save if we are on a simulator
      if (deviceData['isPhysicalDevice'] == false) {
        SharedPrefs().isSimulator = true;
      }

      print(deviceData);
    } on PlatformException {
      deviceData = <String, dynamic>{
        'Error:': 'Failed to get platform version.'
      };
    }
  }

  Map<String, dynamic> _readAndroidBuildData(AndroidDeviceInfo build) {
    return <String, dynamic>{
      'version.securityPatch': build.version.securityPatch,
      'version.sdkInt': build.version.sdkInt,
      'version.release': build.version.release,
      'version.previewSdkInt': build.version.previewSdkInt,
      'version.incremental': build.version.incremental,
      'version.codename': build.version.codename,
      'version.baseOS': build.version.baseOS,
      'board': build.board,
      'bootloader': build.bootloader,
      'brand': build.brand,
      'device': build.device,
      'display': build.display,
      'fingerprint': build.fingerprint,
      'hardware': build.hardware,
      'host': build.host,
      'id': build.id,
      'manufacturer': build.manufacturer,
      'model': build.model,
      'product': build.product,
      'supported32BitAbis': build.supported32BitAbis,
      'supported64BitAbis': build.supported64BitAbis,
      'supportedAbis': build.supportedAbis,
      'tags': build.tags,
      'type': build.type,
      'isPhysicalDevice': build.isPhysicalDevice,
      'systemFeatures': build.systemFeatures,
      'displaySizeInches':
          ((build.displayMetrics.sizeInches * 10).roundToDouble() / 10),
      'displayWidthPixels': build.displayMetrics.widthPx,
      'displayWidthInches': build.displayMetrics.widthInches,
      'displayHeightPixels': build.displayMetrics.heightPx,
      'displayHeightInches': build.displayMetrics.heightInches,
      'displayXDpi': build.displayMetrics.xDpi,
      'displayYDpi': build.displayMetrics.yDpi,
      'serialNumber': build.serialNumber,
    };
  }

  Map<String, dynamic> _readIosDeviceInfo(IosDeviceInfo data) {
    return <String, dynamic>{
      'name': data.name,
      'systemName': data.systemName,
      'systemVersion': data.systemVersion,
      'model': data.model,
      'localizedModel': data.localizedModel,
      'identifierForVendor': data.identifierForVendor,
      'isPhysicalDevice': data.isPhysicalDevice,
      'utsname.sysname:': data.utsname.sysname,
      'utsname.nodename:': data.utsname.nodename,
      'utsname.release:': data.utsname.release,
      'utsname.version:': data.utsname.version,
      'utsname.machine:': data.utsname.machine,
    };
  }

  Map<String, dynamic> _readLinuxDeviceInfo(LinuxDeviceInfo data) {
    return <String, dynamic>{
      'name': data.name,
      'version': data.version,
      'id': data.id,
      'idLike': data.idLike,
      'versionCodename': data.versionCodename,
      'versionId': data.versionId,
      'prettyName': data.prettyName,
      'buildId': data.buildId,
      'variant': data.variant,
      'variantId': data.variantId,
      'machineId': data.machineId,
    };
  }

  Map<String, dynamic> _readWebBrowserInfo(WebBrowserInfo data) {
    return <String, dynamic>{
      'browserName': describeEnum(data.browserName),
      'appCodeName': data.appCodeName,
      'appName': data.appName,
      'appVersion': data.appVersion,
      'deviceMemory': data.deviceMemory,
      'language': data.language,
      'languages': data.languages,
      'platform': data.platform,
      'product': data.product,
      'productSub': data.productSub,
      'userAgent': data.userAgent,
      'vendor': data.vendor,
      'vendorSub': data.vendorSub,
      'hardwareConcurrency': data.hardwareConcurrency,
      'maxTouchPoints': data.maxTouchPoints,
    };
  }

  Map<String, dynamic> _readMacOsDeviceInfo(MacOsDeviceInfo data) {
    return <String, dynamic>{
      'computerName': data.computerName,
      'hostName': data.hostName,
      'arch': data.arch,
      'model': data.model,
      'kernelVersion': data.kernelVersion,
      'majorVersion': data.majorVersion,
      'minorVersion': data.minorVersion,
      'patchVersion': data.patchVersion,
      'osRelease': data.osRelease,
      'activeCPUs': data.activeCPUs,
      'memorySize': data.memorySize,
      'cpuFrequency': data.cpuFrequency,
      'systemGUID': data.systemGUID,
    };
  }

  Map<String, dynamic> _readWindowsDeviceInfo(WindowsDeviceInfo data) {
    return <String, dynamic>{
      'numberOfCores': data.numberOfCores,
      'computerName': data.computerName,
      'systemMemoryInMegabytes': data.systemMemoryInMegabytes,
      'userName': data.userName,
      'majorVersion': data.majorVersion,
      'minorVersion': data.minorVersion,
      'buildNumber': data.buildNumber,
      'platformId': data.platformId,
      'csdVersion': data.csdVersion,
      'servicePackMajor': data.servicePackMajor,
      'servicePackMinor': data.servicePackMinor,
      'suitMask': data.suitMask,
      'productType': data.productType,
      'reserved': data.reserved,
      'buildLab': data.buildLab,
      'buildLabEx': data.buildLabEx,
      'digitalProductId': data.digitalProductId,
      'displayVersion': data.displayVersion,
      'editionId': data.editionId,
      'installDate': data.installDate,
      'productId': data.productId,
      'productName': data.productName,
      'registeredOwner': data.registeredOwner,
      'releaseId': data.releaseId,
      'deviceId': data.deviceId,
    };
  }
}
