import 'package:flutter/material.dart';

import 'package:encrypt_shared_preferences/provider.dart';
import 'package:get/get.dart';

import 'package:f0ckapp/services/api.dart';
import 'package:f0ckapp/controller/settingscontroller.dart';
import 'package:f0ckapp/controller/authcontroller.dart';
import 'package:f0ckapp/controller/localizationcontroller.dart';
import 'package:f0ckapp/controller/themecontroller.dart';
import 'package:f0ckapp/screens/mediadetail.dart';
import 'package:f0ckapp/utils/appversion.dart';
import 'package:f0ckapp/controller/mediacontroller.dart';
import 'package:f0ckapp/screens/mediagrid.dart';
import 'package:f0ckapp/screens/login.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Future.wait([
    EncryptedSharedPreferencesAsync.initialize('VokTnbAbemBUa2j9'),
    MyTranslations.loadTranslations(),
    AppVersion.init(),
  ]);

  Get.put(AuthController());
  Get.put(ApiService());
  Get.put(SettingsController());
  Get.put(MediaController());

  final ThemeController themeController = Get.put(ThemeController());
  final LocalizationController localizationController = Get.put(
    LocalizationController(),
  );

  Get.addTranslations(MyTranslations.instance.keys);
  Get.locale = localizationController.currentLocale.value;

  //Locale systemLocale = WidgetsBinding.instance.platformDispatcher.locale;

  runApp(
    Obx(
      () => MaterialApp(
        locale: Get.locale,
        navigatorKey: Get.key,
        theme: themeController.currentTheme.value,
        debugShowCheckedModeBanner: false,
        initialRoute: '/',
        onGenerateRoute: (RouteSettings settings) {
          final Uri uri = Uri.parse(settings.name ?? '/');

          if (uri.path == '/' || uri.pathSegments.isEmpty) {
            return MaterialPageRoute(builder: (_) => const MediaGrid());
          }

          if (uri.path == '/login') {
            return MaterialPageRoute(builder: (_) => LoginScreen());
          }

          if (uri.pathSegments.length == 1) {
            try {
              final int id = int.parse(uri.pathSegments.first);
              return MaterialPageRoute(
                builder: (_) => MediaDetailScreen(initialId: id),
              );
            } catch (e) {
              return MaterialPageRoute(builder: (_) => const MediaGrid());
            }
          }

          return MaterialPageRoute(builder: (_) => const MediaGrid());
        },
      ),
    ),
  );
}
