import 'package:aitrainer_app/bloc/session/session_bloc.dart';
import 'package:aitrainer_app/bloc/settings/settings_bloc.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/view/login.dart';
import 'package:aitrainer_app/view/menu_page.dart';
import 'package:aitrainer_app/view/registration.dart';
import 'package:aitrainer_app/widgets/dialog_common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'loading.dart';

// ignore: must_be_immutable
class AitrainerHome extends StatefulWidget {
  late _HomePageState _state;
  @override
  State<StatefulWidget> createState() {
    _state = new _HomePageState();
    return _state;
  }
}

class _HomePageState extends State<AitrainerHome> with Logging, Trans {
  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();

    /// We require the initializers to run after the loading screen is rendered
    SchedulerBinding.instance!.addPostFrameCallback((_) {
      runDelayedEvent();
    });
  }

  Future runDelayedEvent() async {
    await Future.delayed(Duration(milliseconds: 500), () async {
      // ignore: close_sinks
      SessionBloc sessionBloc = BlocProvider.of<SessionBloc>(context);
      if (sessionBloc.state != SessionReady()) {
        // ignore: close_sinks
        SettingsBloc settingsBloc = BlocProvider.of<SettingsBloc>(context);
        settingsBloc.context = context;
        sessionBloc.add(SessionStart(settingsBloc: settingsBloc));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    setContext(context);
    return Scaffold(
      key: _scaffoldKey,
      body: BlocConsumer<SessionBloc, SessionState>(listener: (context, state) {
        if (state is SessionFailure) {
          showDialog(
              context: context,
              builder: (BuildContext context) {
                return DialogCommon(
                  title: t("Error"),
                  descriptions: t(state.message),
                  text: "OK",
                  onTap: () => {
                    Navigator.of(context).pop(),
                  },
                  onCancel: () => {
                    Navigator.of(context).pop(),
                  },
                );
              });
        }
      }, builder: (context, state) {
        if (state is SessionInitial) {
          return LoadingScreenMain();
        } else if (state is SessionLoading) {
          log("loading");
          return LoadingScreenMain();
        } else if (state is SessionReady) {
          log("ready menu with " + Cache().startPage);
          if (Cache().startPage == 'login') {
            return LoginPage();
          } else if (Cache().startPage == 'registration') {
            return RegistrationPage();
          } else {
            return MenuPage(parent: 0);
          }
        } else {
          log("home: unknown state");
          return MenuPage(parent: 0);
          //return LoginPage();
        }
      }),
    );
  }

  @override
  void dispose() async {
    super.dispose();
  }
}
