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/app_language.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/view/customer_goal_page.dart';
import 'package:aitrainer_app/view/login.dart';
import 'package:aitrainer_app/view/menu_page.dart';
import 'package:aitrainer_app/widgets/dialog_common.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:matomo_tracker/matomo_tracker.dart';
import 'package:upgrader/upgrader.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, TraceableClientMixin {
  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  String get traceName => 'Home';

  @override
  String get traceTitle => this.widget.toString();

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

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

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('-- FirebaseMessaging: Got a message whilst in the foreground!');
      print('-- FirebaseMessaging: Message data: ${message.data}');

      if (message.notification != null) {
        print('-- FirebaseMessaging: Message also contained a notification: ${message.notification}');
      }
    });
  }

  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);
    final appcastURL = "https://raw.githubusercontent.com/bossanyit/appcast/main/android_rss.xml";
    final cfg = AppcastConfiguration(url: appcastURL, supportedOS: ['android']);
    
    return Scaffold(
        key: _scaffoldKey,
        body: UpgradeAlert(
          upgrader: Upgrader(
              countryCode: AppLanguage().appLocal.toString(), appcastConfig: cfg, messages: MyLocalizedUpgraderMessages(context: context)),
          child: 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 CustomerGoalPage();
              } else {
                return MenuPage(parent: 0);
              }
            } else {
              log("home: unknown state");
              return MenuPage(parent: 0);
            }
          }),
        ));
  }

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

class MyLocalizedUpgraderMessages extends UpgraderMessages with Trans {
  /// Override the message function to provide custom language localization.
  final BuildContext context;
  MyLocalizedUpgraderMessages({required this.context}) : super();
  @override
  String message(UpgraderMessage messageKey) {
    setContext(context);
    switch (messageKey) {
      case UpgraderMessage.body:
        return t('A new version of Workout Test is available!');
      case UpgraderMessage.buttonTitleIgnore:
        return t('Ignore');
      case UpgraderMessage.buttonTitleLater:
        return t('Later');
      case UpgraderMessage.buttonTitleUpdate:
        return t('Update Now');
      case UpgraderMessage.prompt:
        return t('Want to update?');
      case UpgraderMessage.title:
        return t('Update App?');
      case UpgraderMessage.releaseNotes:
        return "";
    }

    // Messages that are not provided above can still use the default values.
    //return super.message(messageKey);
  }
}
