import 'dart:async';
import "dart:convert";
import "dart:io";
import 'package:background_fetch/background_fetch.dart';
import "package:cron/cron.dart";
import "package:daciapackete/arbeitsdaten.dart";
import 'package:daciapackete/globals.dart' as globals;
import "package:daciapackete/ladedaten.dart" as ld;
import "package:daciapackete/sequenzen.dart";
import "package:daciapackete/speicherdaten.dart";
import 'package:flutter/material.dart';
import "package:flutter_localizations/flutter_localizations.dart";
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import "package:springcontrol/card_akkuanzeige.dart";
import "package:springcontrol/card_datenanzeige.dart";
import "package:springcontrol/card_klimastarten.dart";
import "package:springcontrol/card_ladebegrenzung.dart";
import 'package:springcontrol/card_ladenprogrammieren.dart';
import "package:springcontrol/form_config.dart";
import 'package:springcontrol/form_daciaanmeldedaten.dart';
import 'package:springcontrol/form_klimaanlage.dart';
import "package:springcontrol/form_ladeprogramm.dart";
import 'package:springcontrol/form_paypal.dart';
import "package:springcontrol/form_proxyconfig.dart";
import "cards/card_DaciaServerAbfrage.dart";
import "forms/form_fahrttabelle.dart";
import "form_datumzeit_setzen.dart";
import "form_infos.dart";
import 'package:package_info_plus/package_info_plus.dart';
import "package:springcontrol/ladescreen_service.dart";
import 'package:flutter/services.dart';

//import 'package:flutter_gen/gen_l10n/app_localizations.dart';

//import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import 'package:restart_app/restart_app.dart';
import 'package:springcontrol/cards/card_statistik.dart';
import 'form_hilfe.dart';
//import 'package:flutter_localization/flutter_localization.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:http/http.dart' as http;
import "l10n/app_localizations.dart";
import "rest1.dart";
//import "form_statistik.dart";
//mongosh --tls -u userCreatorUser -p 12SpringTest34 www.maschinenlernen.duckdns.org:27017/admin

// Hilfsfunktion


//###############################################

//#################################################


AppLocalizations l10n(BuildContext context) => AppLocalizations.of(context)!;

extension LocalizationExtension on BuildContext {
  AppLocalizations get sp => AppLocalizations.of(this)!;
}

// flutter build apk --release
// flutter build appbundle --release
//  flutter build linux --release
// flutter build windows

// flutter pub run flutter_native_splash:create
// flutter gen-l10n
// dart run flutter_launcher_icons wird wohl nicht gebraucht
var loop = 0;
var loop2 = 0;
String version = "";

//backround_fetch
@pragma('vm:entry-point')
void backgroundFetchHeadlessTask(HeadlessTask task) async {
  // await globals.logging.insertElement("Headless Prozedur");
  BackgroundFetch.finish(task.taskId);
}

//var hintergrund = Hintergrund();
titel() {
  if (globals.daciaAnmeldedaten.daciaName == "DaciaLoginName") {
    return "Dacia-Anmeldedaten eingeben";
  } else {
    return 'Spring Control $version';
  }
}

programmTyp() {
  if ((Platform.isIOS) || (Platform.isAndroid))
  {
    return globals.Programmart.Handy;
  } else return globals.Programmart.PC;
  }


Future<void> cronJobMinute() async {
  //parameter = "cron";
    final cron = Cron();
    try {
      cron.schedule(Schedule.parse('*/1 * * * *'), () async {
        await ablauf(globals.Programmart.PC);
      });
    } on ScheduleParseException {
      print("Cron-Error");
      // "ScheduleParseException" is thrown if cron parsing is failed.
      await cron.close();
    }
}


void main() async {

  WidgetsFlutterBinding.ensureInitialized();
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); // Statusleiste sichtbar lassen
  //await FlutterLocalization.instance.ensureInitialized();
  PackageInfo packageInfo = await PackageInfo.fromPlatform();
  version = packageInfo.version;
  //final version = await getVersion();
  globals.client = programmTyp();
  final dir = await getApplicationDocumentsDirectory();
  globals.dir = dir.path;
  await ld.ladeDaten("lokaleDaten");
  await ld.ladeDaten("arbeitsdaten");
  await ld.ladeDaten("config");
  await ld.ladeDaten("logging");
  final DateTime now = DateTime.now();
  if (globals.arbeitsdaten.letztesSpeichern.isAfter(
      now.subtract(Duration(minutes: globals.config.neustartMinuten)))) {
    await globals.logging.insertElement(
        "Programm war weniger als ${globals.config.neustartMinuten} min aus");
  } else {
    globals.arbeitsdaten = Arbeitsdaten.create();
    await globals.logging.insertElement(
        "Programmneustart. Programm war Länger als ${globals.config.neustartMinuten} min aus");
  }
  //testet ob der wert noch in der Liste ist.
  List liste = [
    globals.config.ladebegrenzungB1,
    globals.config.ladebegrenzungB2,
    globals.config.ladebegrenzungB3,
    globals.config.ladebegrenzungB4,
    globals.config.ladebegrenzungB5,
    globals.config.ladebegrenzungB6
  ];
  if (!liste.contains(globals.config.ladebegrenzung)) {
    globals.config.ladebegrenzung = globals.config.ladebegrenzungB1;
    await speicherDaten("config");
  }
  await ladenAuswertungAusfuehrung();

  // in  android/app/src/main/ AndroidManifest.xml <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

  if ((Platform.isIOS) || (Platform.isAndroid)) {
    var status = await Permission.ignoreBatteryOptimizations.status;
    if (!status.isGranted) {
      var status = await Permission.ignoreBatteryOptimizations.request();
      if (status.isGranted) {
        debugPrint("Good, all your permission are granted, do some stuff");
      } else {
        debugPrint("Do stuff according to this permission was rejected");
      }
    }
  }
//WakelockPlus.enable();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    Locale _locale = Locale(globals.config.sprache, '');
//Multikingual anfang

    return MaterialApp(
      // key: globalkey,
      title: 'Flutter Demo',
      locale: _locale,

      localizationsDelegates: [
        AppLocalizations.delegate, // Add this line
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],

      supportedLocales: [
        Locale("pl"), //Polnisch
        Locale('en'), // English
        Locale('de'), // Deutschu
        Locale("fr"), //Französisch
        Locale("es"), //Spanisch
        Locale("ro") //Rumänisch
      ],
      localeResolutionCallback: (locale, supportedLocales) {
        // Fallback, falls keine passende Sprache gefunden wird
        return locale != null
            ? supportedLocales.firstWhere(
                (supportedLocale) =>
                    supportedLocale.languageCode == locale.languageCode,
                orElse: () => const Locale('en'), // Fallback-Sprache
              )
            : const Locale('en'); // Fallback-Sprache
      },
      routes: {
        "/FormDateTimeSet": (context) => FormDateTimeSet(),
       // "/CardLadebegrenzung": (context) => CardLadebegrenzung(),
        "/FormConfig": (context) => FormConfig(),
        "/FormLadeprogramm": (context) => FormLadeprogramm(),
        "/FormKlimaanlage": (context) => FormKlimaanlage(),
        "/FormServerConfig": (context) => FormServerConfig(),
        "/FormDaciaAnmeldedaten": (context) => FormDaciaAnmeldedaten(),
        "/FormInfos": (context) => FormInfos(),
        "/FormPayPal": (context) => FormPayPal(),
        //"/FahrtListeFormular": (context) => FahrtListeFormular(),
         "/FahrtTabelle": (context) => FormFahrtTabelle(),
        "/FormHilfe": (context) => const FormHilfe(),

      },
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo),
        //brightness: Brightness.light,
        useMaterial3: true,
      ),
      debugShowCheckedModeBanner: false,
      home: MyHomePage(title: titel()),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void callSetState() {
    setState(() {
      CardDatenanzeige();
      CardAkkuanzeige();
      CardLadenProgrammieren(callSetState);
      KlimaStarten();
      CardStatistik();
      CardDaciaServerAbfrage();
    });
  }

  @override
  void initState() {
    super.initState();
    //WakelockPlus.enable();
    if (programmTyp() == globals.Programmart.Handy) {
      timerRefreshLokal();
      initPlatformState();
    } else {
      cronJobMinute();
    }
    // print("charging 2${globals.ladeKlimaKonfig.charging}");
  }

  Future<void> timerRefreshLokal() async {
    Timer.periodic(Duration(seconds: globals.config.sekundenRefreshScreen),
        (timer) async {
      setState(() {
        ld.ladeDaten("arbeitsdaten");
        ld.ladeDaten("ladeKlimaKonfig");
        ld.ladeAutodaten();
      });
    });
  }

  Future<void> initPlatformState() async {
    int status = await BackgroundFetch.configure(
        BackgroundFetchConfig(
          minimumFetchInterval: globals.config.zyklus,
          forceAlarmManager: true,
          stopOnTerminate: true,
          startOnBoot: true,
          enableHeadless: true,
          requiresBatteryNotLow: false,
          requiresCharging: false,
          requiresStorageNotLow: false,
          requiresDeviceIdle: false,
          requiredNetworkType: NetworkType.NONE,
        ), (String taskId) async {
      var dir = await getApplicationDocumentsDirectory();
      globals.dir = dir.path;
      //await globals.logging.insertElement("BF 1 start ID $taskId ");
      //await globals.logging.insertElement("Loop $loop");
      loop++;
      await ladenAuswertungAusfuehrung();
      // await globals.logging.insertElement("BF 1 nach start ID $taskId ");
      BackgroundFetch.finish(taskId);
    }, (String taskId) async {
      // await globals.logging.insertElement("BF 2 Timeout ID $taskId");
      BackgroundFetch.finish(taskId);
    });
    // await globals.logging.insertElement("BF 3 Konfiguration OK $status");
    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
        actions: [
          PopupMenuButton(onSelected: (value) async {
            switch (value) {
              case "Konfiguration-Server":
                await Navigator.pushNamed(context, "/FormServerConfig");
              // setState(() {});
              case "Konfiguration":
                await Navigator.pushNamed(context, "/FormConfig");
                setState(() {});
              case "DaciaAnmeldedaten":
                await Navigator.pushNamed(context, "/FormDaciaAnmeldedaten");
              case "Log":
                await Navigator.pushNamed(context, "/FormInfos");
              case "Cappuccino":
                await Navigator.pushNamed(context, "/FormPayPal");
              case "Liste1":
                await Navigator.pushNamed(context, "/FahrtListeFormular");
              case "Statistik":
                await Navigator.pushNamed(context, "/FahrtTabelle");
              case "Hilfe":
                print("Hilfe");
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const FormHilfe()),
                );
            }
          },
              //icon: Icon(Icons.more_vert, color: Colors.black)
              itemBuilder: (BuildContext context) {
            return [
              PopupMenuItem(
                value: "Konfiguration",
                child: Text(context.sp.konfiguration),
              ),
              PopupMenuItem(
                value: "Konfiguration-Server",
                child: Text(context.sp.konfigurationProxyserver),
              ),
              PopupMenuItem(
                value: "DaciaAnmeldedaten",
                child: Text(context.sp.daciaAnmeldedaten),
              ),
              PopupMenuItem(
                value: "Log",
                child: Text(context.sp.log),
              ),
              PopupMenuItem(
                value: "Cappuccino",
                child: Text(context.sp.cappuccino),
              ),
              //PopupMenuItem(
              //  value: "Liste1",
              //  child: Text("liste1"),
              //),
              PopupMenuItem(
                value: "Statistik",
                child: Text("Statistik"),
              ),
              //untermenü
              PopupMenuItem<String>(
                value: 'language',
                child: Row(
                  children: [
                    Expanded(
                      child: Text(AppLocalizations.of(context)!.sprache),
                    ),
                    PopupMenuButton<String>(
                      onSelected: (String value) {
                        globals.config.sprache = value;
                        speicherDaten("config"); // Englisch
                        Restart.restartApp(
                          // Customizing the notification message only on iOS
                          notificationTitle: 'Restarting App',
                          notificationBody:
                              'Please tap here to open the app again.',
                        );
                      },
                      itemBuilder: (BuildContext context) {
                        return [
                          // Untermenüpunkte
                          PopupMenuItem<String>(
                            value: 'en',
                            child: Text('English'),
                          ),
                          PopupMenuItem<String>(
                            value: 'de',
                            child: Text('Deutsch'),
                          ),
                          PopupMenuItem<String>(
                            value: 'pl',
                            child: Text('Polski'),
                          ),
                          PopupMenuItem<String>(
                            value: 'fr',
                            child: Text('Français'),
                          ),
                          PopupMenuItem<String>(
                            value: 'es',
                            child: Text('Español'),
                          ),
                          PopupMenuItem<String>(
                            value: 'ro',
                            child: Text('Română'),
                          ),
                        ];
                      },
                      icon: Icon(
                          Icons.arrow_right), // Pfeil-Icon für das Untermenü
                    ),
                  ],
                ),
              ),
              PopupMenuItem(
                value: "Hilfe",
                child: Text("Hilfe"),
              ),
            ];
          })
        ],
      ),

      body: SafeArea (
      child: Center(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              CardDatenanzeige(),
              CardAkkuanzeige(),
              CardLadenProgrammieren(callSetState),
              //CardLadenProgrammieren(),
              KlimaStarten(),

             CardStatistik(),
              CardDaciaServerAbfrage(),

              //  CardServerkontakt(),
            ],
          ),
        ),
      ),

      ),
/*
      // xxxxxxxxxxxxxxxx
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            label: 'Einstellungen',
          ),
        ],
      ),
      // xxxxxxxxxxxxxxxxx
*/

      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          LadescreenService.startLadescreen(context);
          //print("Liste Globals 5 ${globals.arbeitsdaten.verbindungen}");
          if (globals.config.logGenau == true) {
            await globals.logging.insertElement(context.sp.vordergrundButton);
          }
          globals.ladeKlimaKonfig.buttonHoleAutoDaten = true;
          speicherDaten("ladeKlimaKonfig");
          await ladenAuswertungAusfuehrung();
         // globals.arbeitsdaten.buttonHoleAutoDaten = false;
          LadescreenService.stopLadescreen(context);
          setState(() {});
        },
        // tooltip: context.sp.datenabrufVomServer,
        child: const Icon(Icons.refresh_rounded),
      ),
      //floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
    );

  }

}
