import 'package:comunic/helpers/groups_helper.dart';
import 'package:comunic/ui/screens/authorized_group_page_screen.dart';
import 'package:comunic/ui/screens/group_access_denied_screen.dart';
import 'package:comunic/ui/widgets/safe_state.dart';
import 'package:comunic/utils/intl_utils.dart';
import 'package:comunic/utils/ui_utils.dart';
import 'package:flutter/material.dart';

/// Group screen
///
/// @author Pierre Hubert

class GroupPageScreen extends StatefulWidget {
  final int groupID;

  const GroupPageScreen({Key key, @required this.groupID})
      : assert(groupID != null),
        super(key: key);

  @override
  _GroupPageScreenState createState() => _GroupPageScreenState();
}

class _GroupPageScreenState extends SafeState<GroupPageScreen> {
  int get groupID => widget.groupID;

  GetAdvancedInfoResult _getGroupResult;
  var error = false;

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

  @override
  Widget build(BuildContext context) {
    if (error)
      return buildErrorCard(tr("Could not load information about the group!"),
          actions: [
            MaterialButton(
              onPressed: () => _refreshPage(),
              child: Text(tr("Try again").toUpperCase()),
            )
          ]);

    // If we are still loading the page
    if (_getGroupResult == null) return buildCenteredProgressBar();

    // Check if access to the group was denied
    if (_getGroupResult.status == GetAdvancedInfoStatus.ACCESS_DENIED)
      return GroupAccessDeniedScreen(
        groupID: groupID,
        onMembershipAcquired: () => _refreshPage(),
      );

    // Now we can show group page
    return AuthorizedGroupPageScreen(
      advancedGroupInfo: _getGroupResult.info,
      needRefresh: () => _refreshPage(),
    );
  }

  /// Refresh the page
  Future<void> _refreshPage() async {
    try {
      setState(() {
        error = false;
        _getGroupResult = null;
      });

      // Get information about the group
      final result = await GroupsHelper().getAdvancedInfo(groupID);

      setState(() {
        _getGroupResult = result;
      });
    } catch (e) {
      print(e);
      setState(() {
        error = true;
      });
    }
  }
}