import 'package:daciapackete/configproxyserver.dart';
import 'package:daciapackete/globals.dart' as globals;
import "package:daciapackete/mongodb.dart" as mongodb;
import 'package:daciapackete/speicherdaten.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
//import 'package:springcontrol/ladedaten.dart';
import 'package:daciapackete/ladedaten.dart';
import "showalertdialog.dart";
//import 'package:daciapackete/speicherdaten.dart' as speicherdaten;
import "package:springcontrol/ladescreen_service.dart";

class FormServerConfig extends StatefulWidget {
  const FormServerConfig({super.key});

  @override
  State<FormServerConfig> createState() => _FormServerConfigState();
}

class _FormServerConfigState extends State<FormServerConfig> {
  // const themeBox = 'hiveThemeBox';
  // void main() async {
  // await Hive.initFlutter();
  // await Hive.openBox(themeBox);

  ConfigProxyServer configProxyServer = globals.configProxyServer.copy();
  var proxyValue = globals.configProxyServer.proxyBenutzen;
  var userErzeugt = globals.configProxyServer.userErzeugt;
  var deleteServerLog = globals.configProxyServer.deleteServerLog;
  bool _obscureText = true;
  bool _obscureText2 = true;
  bool zweithandy = false;

  buttonText() {
    if (userErzeugt == true) {
      if (zweithandy) {
        return"Zweithandy koppeln";
      } else {
        return "Test Anmeldung";
      }
    } else {
      return "User Anlegen";
    }
  }

  titelText() {
    if (proxyValue == true) {
      return "Proxy ist Aktiv";
    } else {
      return "Proxy ist aus";
    }
  }

  datenSpeichern() async {
   //LadescreenService.startLadescreen(context);
    configProxyServer.proxyBenutzen = proxyValue;
    configProxyServer.userErzeugt = userErzeugt;
    configProxyServer.deleteServerLog = deleteServerLog;
    globals.configProxyServer = configProxyServer;
    await speicherDaten("proxydaten");
    await speicherDaten("arbeitsdaten");
    await speicherDaten("daciaAnmeldedaten");
    await speicherDaten("config");
    await speicherDaten("ladeKlimaKonfig");
    await speicherDaten("arbeitsdaten");
    await speicherDaten("extern");
  // LadescreenService.stopLadescreen(context);
  }

  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return PopScope(
      onPopInvokedWithResult: (didPop, result) async {
        await datenSpeichern();
        //dispose();
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text(titelText()),
          actions: [
            Switch(
              activeColor: Colors.green,
              activeTrackColor: Colors.grey.shade400,
              inactiveThumbColor: Colors.red.shade600,
              inactiveTrackColor: Colors.grey.shade400,
              value: proxyValue,
              onChanged: (value) async {
                //Hive.box(themeBox).put('darkMode', !value);
                if (proxyValue == true) {
                  globals.configProxyServer.proxyBenutzen = false;
                  String ergebnisChangeProxy = await changeProxy();
                  proxyValue = false;
                  await speicherDaten("proxydaten");

                } else {
                  if (userErzeugt == false) {
                    showAlertDialog(
                        context, "Proxy Fehler", "Erst User Erzeugen", "ok");
                  } else {
                    proxyValue = true;
                    //globals.daciaAnmeldedaten.proxyBenutzen = proxyValue;
                    globals.configProxyServer.proxyBenutzen = true;
                    await speicherDaten("proxydaten");
                  }
                }
                setState(() {});
              },
            ),
          ],
          //centerTitle: true,
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        ),
        body: Center(
          child: SingleChildScrollView(
            child: Form(
              key: _formKey,
              child: Column(
                //mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Card(
                    child: Padding(
                      padding: const EdgeInsets.all(8),
                      child: Column(
                        children: <Widget>[
                          const ListTile(
                            title: Text("Server Angaben"),
                          ),
                          //Switch
                          Card(
                            child: Padding(
                              padding: const EdgeInsets.all(8),
                              child: Column(
                                children: <Widget>[
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      const Text("Datenbank-User angelegt"),
                                      Switch(
                                        activeColor: Colors.green,
                                        activeTrackColor: Colors.grey.shade400,
                                        inactiveThumbColor: Colors.red.shade600,
                                        inactiveTrackColor:
                                            Colors.grey.shade400,
                                        value: userErzeugt,
                                        onChanged: (value) {
                                          //Hive.box(themeBox).put('darkMode', !value);
                                          if (userErzeugt == true) {
                                            userErzeugt = false;
                                            proxyValue = false;
                                          } else {
                                            userErzeugt = true;
                                          }
                                          setState(() {});
                                        },
                                      ),
                                    ],
                                  ),


                                  Row(
                                    mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                    children: [
                                      const Text("Server Log löschen"),
                                      Switch(
                                        activeColor: Colors.green,
                                        activeTrackColor: Colors.grey.shade400,
                                        inactiveThumbColor: Colors.red.shade600,
                                        inactiveTrackColor:
                                        Colors.grey.shade400,
                                        value: deleteServerLog,
                                        onChanged: (value) {
                                          //Hive.box(themeBox).put('darkMode', !value);
                                          deleteServerLog = value;
                                          setState(() {});
                                        },
                                      ),
                                    ],
                                  ),

                                  if (userErzeugt == false) ...[
                                    Row(
                                      mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                      children: [
                                        const Text("Zweithandy hinzufügen"),
                                        Switch(
                                          activeColor: Colors.green,
                                          activeTrackColor: Colors.grey.shade400,
                                          inactiveThumbColor: Colors.red.shade600,
                                          inactiveTrackColor:
                                          Colors.grey.shade400,
                                          value: zweithandy,
                                          onChanged: (value) {
                                            //Hive.box(themeBox).put('darkMode', !value);
                                            zweithandy = value;
                                            if(zweithandy) {
                                              userErzeugt = true;
                                            }
                                            setState(() {});
                                          },
                                        ),
                                      ],
                                    ),



                                    TextFormField(
                                      autocorrect: false,
                                      keyboardType: TextInputType.text,
                                      decoration: const InputDecoration(
                                          labelText: "Öffentlicher User"),
                                      initialValue: (configProxyServer
                                          .userCreateUserName),
                                      validator: (ucu) {
                                        if (ucu!.isEmpty) {
                                          return 'Bitte einen Benutzernamen eingeben';
                                        }
                                        return null;
                                      },
                                      onChanged: (ucu) => setState(() {
                                        configProxyServer.userCreateUserName =
                                            ucu;
                                        //globals.configProxyServer.userCreateUserName = ucu;
                                      }),
                                    ),

                                    TextFormField(
                                      obscureText: _obscureText,
                                      autocorrect: false,
                                      keyboardType: TextInputType.text,
                                      initialValue: (configProxyServer
                                          .userCreateUserPasswort),
                                      validator: (dp) {
                                        if (dp!.isEmpty) {
                                          return 'Bitte ein Passwort eingeben';
                                        }
                                        return null;
                                      },
                                      decoration: InputDecoration(
                                        labelText: "Passwort",
                                        suffixIcon: IconButton(
                                          icon: Icon(
                                            _obscureText
                                                ? Icons.visibility
                                                : Icons.visibility_off,
                                          ),
                                          onPressed: () {
                                            setState(() {
                                              _obscureText = !_obscureText;
                                            });
                                          },
                                        ),
                                      ),
                                      onChanged: (ucupw) => setState(() =>
                                          configProxyServer
                                              .userCreateUserPasswort = ucupw),
                                    ),
                                  ],
                                ],
                              ),
                              // ),
                              //neu ende
                            ),
                          ),
                          //Switch ende
                          TextFormField(
                            autocorrect: false,
                            keyboardType: TextInputType.text,
                            inputFormatters: [
                              FilteringTextInputFormatter.allow(
                                  RegExp(r'[a-zA-Z0-9]')),
                            ],
                            decoration:
                                const InputDecoration(labelText: "Login Name"),
                            initialValue: (configProxyServer.dbUserName),
                            validator: (dn) {
                              if (dn!.isEmpty) {
                                return 'Bitte einen Benutzernamen eingeben';
                              }
                              return null;
                            },
                            onChanged: (dn) => setState(
                                () => configProxyServer.dbUserName = dn),
                          ),
                          TextFormField(
                            obscureText: _obscureText2,
                            autocorrect: false,
                            keyboardType: TextInputType.text,
                            initialValue: (configProxyServer.dbPasswort),
                            validator: (dp) {
                              if (dp!.isEmpty) {
                                return 'Bitte ein Passwort eingeben';
                              }
                              return null;
                            },
                            decoration: InputDecoration(
                              labelText: "Passwort",
                              suffixIcon: IconButton(
                                icon: Icon(
                                  _obscureText2
                                      ? Icons.visibility
                                      : Icons.visibility_off,
                                ),
                                onPressed: () {
                                  setState(() {
                                    _obscureText2 = !_obscureText2;
                                  });
                                },
                              ),
                            ),
                            onChanged: (dp) => setState(
                                () => configProxyServer.dbPasswort = dp),
                          ),
                          TextFormField(
                            autocorrect: false,
                            keyboardType: TextInputType.text,
                            decoration:
                                const InputDecoration(labelText: "Adress-Name"),
                            initialValue: (configProxyServer.dbAdresse),
                            // obscureText: true,
                            onChanged: (dp) => setState(
                                () => configProxyServer.dbAdresse = dp),
                          ),
                          TextFormField(
                            autocorrect: false,
                            keyboardType: TextInputType.text,
                            decoration:
                                const InputDecoration(labelText: "Port"),
                            initialValue: (configProxyServer.dbPort),
                            //obscureText: true,
                            onChanged: (dp) =>
                                setState(() => configProxyServer.dbPort = dp),
                          ),
                          ElevatedButton(
                            child: Text(buttonText()),
                            onPressed: () async {
                              //print(configProxyServer.toJson());
                              if (userErzeugt == false) {
                                var em = await mongodb.createMongoUserMitDb(
                                    configProxyServer);
                                if (em == "ok") {
                                  userErzeugt = true;
                                  await datenSpeichern();
                                  setState(() {});
                                } else {
                                  print("em nicht null $em");
                                  showDialog<String>(
                                    context: context,
                                    builder: (BuildContext context) =>
                                        AlertDialog(
                                      title: const Text(
                                          'Datenbank User anlegen Fehler:'),
                                      content: Text(em),
                                      actions: <Widget>[
                                        TextButton(
                                          onPressed: () =>
                                              Navigator.pop(context, 'OK'),
                                          child: const Text('OK'),
                                        ),
                                      ],
                                    ),
                                  );
                                }
                              } else {
                                LadescreenService.startLadescreen(context);
                                var ergebnis = await mongodb
                                    .testeZugang(configProxyServer);
                                LadescreenService.stopLadescreen(context);
                                if (ergebnis == "") {
                                  if (zweithandy) {
                                    globals.configProxyServer = configProxyServer;
                                   // ladeDatenHoleAutodaten();
                                    //LadebildschirmApp s;
                                    LadescreenService.startLadescreen(context);
                                    await copyMongoLokal();
                                    proxyValue = true;
                                    globals.configProxyServer.proxyBenutzen = true;
                                    zweithandy = false;
                                    LadescreenService.stopLadescreen(context);
                                    setState(() {});
                                    showAlertDialog(context, "Zweithandy",
                                        "Anmeldung ok", "ok");
                                  } else {
                                    showAlertDialog(context, "Datenbank Test",
                                        "Anmeldung ok", "ok");
                                  }
                                } else {
                                  showAlertDialog(context, "Datenbank Problem",
                                      ergebnis, "ok");
                                }
                              }
                            },
                          ),
                          if (userErzeugt == true) ...[
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                ElevatedButton(
                                  child: const Text("Passwort Ändern"),
                                  onPressed: () async {
                                    LadescreenService.startLadescreen(context);
                                    var ergebnis1 =
                                        await mongodb.changeMongoUserPw(
                                            globals.configProxyServer,
                                            configProxyServer.dbPasswort);
                                    LadescreenService.stopLadescreen(context);
                                    print("ergebnis");
                                    print(ergebnis1);
                                    if (ergebnis1 == "ok") {
                                      await datenSpeichern();
                                      setState(() {});
                                      showAlertDialog(context, "Datenbank",
                                          "Passwort Änderung ok.", "ok");
                                    } else {
                                      showAlertDialog(context, "Datenbank",
                                          ergebnis1, "ok");
                                    }
                                  },
                                  // child: const Text("Passwort Ändern"),
                                ),
                                ElevatedButton(
                                  child: const Text("User Löschen"),
                                  onPressed: () async {
                                    LadescreenService.startLadescreen(context);
                                    var ergDelete =
                                        await mongodb.deleteMongoUser(
                                            globals.configProxyServer);
                                    LadescreenService.stopLadescreen(context);
                                    print("ergebnis");
                                    print(ergDelete);
                                    if (ergDelete == "ok") {
                                      userErzeugt = false;
                                      proxyValue = false;
                                      await datenSpeichern();
                                      setState(() {});
                                      showAlertDialog(context, "Datenbank",
                                          "Löschen User ok.", "ok");
                                    } else {
                                      showAlertDialog(context, "Datenbank",
                                          ergDelete, "ok");
                                    }
                                  },
                                ),
                              ],
                            ),
                          ],
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
