import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jiffy/jiffy.dart';
import 'package:marianum_mobile/data/timetable/timetableProps.dart';
import 'package:marianum_mobile/screen/login/login.dart';
import 'package:marianum_mobile/widget/loadingSpinner.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'app.dart';
import 'data/chatList/chatListProps.dart';
import 'data/chatList/chatProps.dart';
import 'data/accountModel.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  ByteData data = await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem');
  SecurityContext.defaultContext.setTrustedCertificatesBytes(data.buffer.asUint8List());

  runApp(
      MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (context) => AccountModel()),
          ChangeNotifierProvider(create: (context) => TimetableProps()),
          ChangeNotifierProvider(create: (context) => ChatListProps()),
          ChangeNotifierProvider(create: (context) => ChatProps()),
        ],
        child: const Main(),
      )
  );
}

class Main extends StatefulWidget {
  const Main({Key? key}) : super(key: key);

  @override
  State<Main> createState() => _MainState();
}

class _MainState extends State<Main> {
  static const Color marianumRed = Color.fromARGB(255, 153, 51, 51);

  final Future<SharedPreferences> _storage = SharedPreferences.getInstance();

  @override
  void initState() {
    super.initState();
    Jiffy.locale("de");
    _storage.then((SharedPreferences preferences) => preferences.getBool("loggedIn") ?? false).then((value) => {
      if(value) {
        Provider.of<AccountModel>(context, listen: false).login()
      } else {
        Provider.of<AccountModel>(context, listen: false).logout()
      }
    });

  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,

      title: 'Marianum Fulda',
      theme: ThemeData(
        brightness: Brightness.light,
        primaryColor: marianumRed,
        hintColor: marianumRed,
        inputDecorationTheme: const InputDecorationTheme(
           border: UnderlineInputBorder(borderSide: BorderSide(color: marianumRed)),
        ),
        appBarTheme: const AppBarTheme(
          backgroundColor: marianumRed,
        ),
        progressIndicatorTheme: const ProgressIndicatorThemeData(
          color: marianumRed,
        ),
      ),

      home: FutureBuilder<SharedPreferences>(
        future: _storage,
        builder: (BuildContext context, AsyncSnapshot<SharedPreferences> snapshot) {

          if(snapshot.hasData) {
            return Consumer<AccountModel>(
              builder: (context, accountModel, child) {
                return accountModel.isLoggedIn ? const App() : const Login();
              },
            );
          } else {
            return const LoadingSpinner();
          }
        },
      )
    );
  }
}