import 'dart:async';
import 'dart:io';
//import "package:sprin";
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_proxyconfig.dart";
//import 'package:springcontrol/hintergrund.dart';
import "package:springcontrol/ladedaten.dart";
import "package:daciapackete/arbeitsdaten.dart";
import "package:daciapackete/auswertungen.dart";
import 'package:daciapackete/globals.dart' as globals;
import "package:daciapackete/logging.dart" as logging;
import "package:daciapackete/speicherdaten.dart";
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wakelock_plus/wakelock_plus.dart';
import 'package:workmanager/workmanager.dart';
import "form_datumzeit_setzen.dart";
import "form_infos.dart";
import "package:audioplayers/audioplayers.dart";
const iOSBackgroundProcessingTask =
    "be.tramckrijte.workmanagerExample.iOSBackgroundProcessingTask";
const iOSBackgroundAppRefresh =
    "be.tramckrijte.workmanagerExample.iOSBackgroundAppRefresh";
//const iOSBackgroundProcessingTask = "be.tramckrijte.workmanagerExample.iOSBackgroundProcessingTask";

timerAbrufAuswertungOhne() async {
  print("timerAbrufAuswertungOhne2-Anfang");
  Timer.periodic(Duration(minutes: globals.config.zyklus), (timer) async {
    await ladeDaten();
    await Auswertungen().auswertungLademanagement();
    await Auswertungen().auswertungKlimamanagement();
    globals.arbeitsdaten.letztesSpeichern = DateTime.now();
    await speicherDaten("arbeitsdaten");
  });
}

timerAudio() async {
  Timer.periodic(Duration(minutes: 1), (timer) async {
    //callSetState();
    //await logging.insertElement("timer refresh");
    final player = AudioPlayer();
    //await player.setAsset("audio/1h.mp3");
    //player.play();
    player.play(AssetSource("audio/1m.mp3"));

  });
}
/*
@pragma('vm:entry-point')
void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) async {
    await ladeArbeitsdaten();
    await ladeConfig();
    if (globals.config.logGenau == true) {
      await logging.insertElement("workmanager Start ");
    }
    for (var i = 0; i < 30; i = i + globals.config.zyklus) {
   // while (true) {
      await ladeArbeitsdaten();
      final DateTime now =
      DateTime.now().subtract(Duration(minutes: globals.config.zyklus));
      if (globals.arbeitsdaten.letztesSpeichern.compareTo(now) <= 0) {
        await ladeDaten();
        await Auswertungen().auswertungLademanagement();
        await Auswertungen().auswertungKlimamanagement();
      } else {
        print("ohne Ausführung");
        if (globals.config.logGenau == true) {
          logging.insertElement("ohne Ausführung");
        }
      }
      await Future.delayed(Duration(minutes: globals.config.zyklus));
    }
     return Future.value(true);
  });
}
*/


@pragma('vm:entry-point')
void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) async {
    print("workmanager start $task");

    timerAudio();
    print("nach audio vor arbeitsdaten");
    await ladeArbeitsdaten();
    print ("nach arbeitsdaten");
    //print(globals.arbeitsdaten.verbindungen);
    print("lade config");
    await ladeConfig();
    if (globals.config.logGenau == true) {
      await logging.insertElement("workmanager Start $task");
    }
    //for (var i = 0; i < 15; i = i + globals.config.zyklus) {
    print("vor schleife");
    while (true) {

      print("000");
      await ladeArbeitsdaten();
      await ladeConfig();
      final DateTime nowMinusZyklus =
          DateTime.now().subtract(Duration(minutes: (globals.config.zyklus - 2)));
      print("Now & Now - Zyklus & Letztes Speichern");
      print(DateTime.now());
      print (nowMinusZyklus);
      print(globals.arbeitsdaten.letztesSpeichern);
     // await logging.insertElement("Zyklus $task");
      print("aaaaa");
    //  if (globals.arbeitsdaten.letztesSpeichern.compareTo(nowMinusZyklus) <= 0) {
        await ladeDaten();
        await Auswertungen().auswertungLademanagement();
        await Auswertungen().auswertungKlimamanagement();
        globals.arbeitsdaten.letztesSpeichern = DateTime.now();
        await speicherDaten("arbeitsdaten");
    //  }
    /*
    else {
        print("ohne Ausführung");
        if (globals.config.logGenau == true) {
        await   logging.insertElement("ohne Ausführung $task");

     */
      //  }
     // }

print("22222");
      await Future.delayed(Duration(minutes: globals.config.zyklus));
print("3333");
    }
    return Future.value(true);
  });
}



//var hintergrund = Hintergrund();

titel() {
  if (globals.daciaAnmeldedaten.daciaName == "DaciaLoginName") {
    return "Dacia-Anmeldedaten eingeben";
  } else {
    return 'Spring Control 0.1.2';
  }
}

void main() async {
  print("Progarmmstart");
  WidgetsFlutterBinding.ensureInitialized();
  globals.client = true;
  await ladeArbeitsdaten();
  await ladeConfig();
  final DateTime now = DateTime.now();
  if (globals.arbeitsdaten.letztesSpeichern.isAfter(
      now.subtract(Duration(minutes: globals.config.neustartMinuten)))) {
    await logging.insertElement(
        "Programm war weniger als ${globals.config.neustartMinuten} min aus");
  } else {
    List liste = [...globals.arbeitsdaten.verbindungen];
    globals.arbeitsdaten = Arbeitsdaten.create();

    //globals.arbeitsdaten.verbindungen.add (liste);
    await logging.insertElement(
        "Programmneustart. Programm war Länger als ${globals.config.neustartMinuten} min aus");
  }

  //print(globals.arbeitsdaten.verbindungen);
 // await Future.delayed(Duration(seconds: 5));
  await ladeDaten();

  // in  android/app/src/main/ AndroidManifest.xml <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
  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();
// timerAbrufAuswertungOhne();
  //workmanager ende
 // Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
  //WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // key: globalkey,
      title: 'Flutter Demo',
      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(),
      },
      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);
      //CardLadenProgrammieren();
      KlimaStarten();
    });
  }

  timerRefreshLokal() async {
  Timer.periodic(Duration(seconds: globals.config.sekundenRefreshScreen), (timer) async {
  //callSetState();
  //await logging.insertElement("timer refresh");

  setState(() {
    ladeArbeitsdaten();
    ladeKlimaKonfigdaten();
    ladeDBAutodaten();
  });
  });}




  @override

  void initState() {
    super.initState();
    WakelockPlus.enable();
   // timerRefresh(setState);
    //Future<void> wm1;
    //Future<void> wm2;
    //await Future.delayed(Duration(seconds: 5));
    //print("Sleep 5 s");
   // print("Liste Globals 3 ${globals.arbeitsdaten.verbindungen}");
    //sleep(Duration(seconds:5));
    print("register wm");

   Workmanager().initialize(callbackDispatcher, isInDebugMode: false);
  //  if (Platform.isIOS) {
  //    print("IST IOS**********");

      Workmanager().registerOneOffTask("task-identifyer", "task-identifyer");
    //  Workmanager().registerPeriodicTask("task-identifyer", "task-identifyer");
      //vor ios 13
/*
       Workmanager().registerPeriodicTask(   //wm2 =
        iOSBackgroundAppRefresh,
        iOSBackgroundAppRefresh,
       // initialDelay: Duration(seconds: 10),
       // frequency: const Duration(minutes: 15), // Ignored on iOS, rather set in AppDelegate.swift
        //inputData: ... // Not supported
      );


 */

   // } else {
    //  print("NIX IOS------------");
      //globals.config.verbindungsart = false;
      // if (globals.config.verbindungsart == true) {
   /*
      Workmanager()  //wm1 =
          .registerOneOffTask("task-identifier", "simpleTask", tag: "tag");
      print("Register single task");

    */
      // } else {
      /*
   Workmanager().registerPeriodicTask( //wm2 =
        "1",
        "periodeTask",
        frequency: const Duration(minutes: 15),
        inputData: <String, dynamic>{'key': 'value'},
      );

       */
     // print("Register multi Task");
      // }
   // }

    print("Starte wm1");
   //  wm1;
    print("Starte wm2");
   // wm2;
    print("Starte Timer refresh");
   //final player = AudioPlayer();
    //await player.setAsset("audio/1h.mp3");
    //player.play();
   // player.play(AssetSource("audio/10s.mp3"));
    //timerAudio();
   // timerRefreshLokal();
    //timerAbrufAuswertungOhne();
    print("Starte Hauptprogramm");

     // Log enthält nur einmla das Laden


    //var timerRefresh;
/*
    timerRefresh = async {

      Timer.periodic(Duration(seconds: globals.config.sekundenRefreshScreen), (timer) async {
        //callSetState();
        await ladeDaten();
        await Auswertungen().auswertungLademanagement();
        await Auswertungen().auswertungKlimamanagement();
        globals.arbeitsdaten.letztesSpeichern = DateTime.now();
        await speicherDaten("arbeitsdaten");
      }


 */
     }

  @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 "Infos":
                await Navigator.pushNamed(context, "/FormInfos");
            }
          },
              //icon: Icon(Icons.more_vert, color: Colors.black)
              itemBuilder: (BuildContext context) {
            return [
              const PopupMenuItem(
                value: "Konfiguration",
                child: Text("Konfiguration"),
              ),
              const PopupMenuItem(
                value: "Konfiguration-Server",
                child: Text("Konfiguratuon Proxyserver"),
              ),
              const PopupMenuItem(
                value: "DaciaAnmeldedaten",
                child: Text("Dacia Anmeldedaten"),
              ),
              const PopupMenuItem(
                value: "Infos",
                child: Text("Infos"),
              ),
            ];
          })
        ],
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              CardDatenanzeige(),
              CardAkkuanzeige(),
              CardLadenProgrammieren(callSetState),
              //CardLadenProgrammieren(),
              KlimaStarten(),
              //  CardServerkontakt(),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          //print("Liste Globals 5 ${globals.arbeitsdaten.verbindungen}");
         await logging.insertElement("Vordergrund Button");
          await ladeArbeitsdaten();
          await ladeAutodaten();
          setState(() {});
        },
        tooltip: 'Datenabruf vom Server',
        child: const Icon(Icons.refresh_rounded),
      ),
    );
  }
}
