import 'package:comunic/helpers/conversations_helper.dart';
import 'package:comunic/helpers/users_helper.dart';
import 'package:comunic/lists/users_list.dart';
import 'package:comunic/models/conversation.dart';
import 'package:comunic/ui/screens/update_conversation_screen.dart';
import 'package:comunic/ui/widgets/comunic_back_button_widget.dart';
import 'package:comunic/utils/intl_utils.dart';
import 'package:comunic/utils/ui_utils.dart';
import 'package:flutter/material.dart';

/// Update a conversation route
///
/// @author Pierre HUBERT

class UpdateConversationRoute extends StatefulWidget {
  final int conversationID;

  const UpdateConversationRoute({Key key, this.conversationID})
      : assert(conversationID != null),
        super(key: key);

  @override
  State<StatefulWidget> createState() => _UpdateConversationRoute();
}

class _UpdateConversationRoute extends State<UpdateConversationRoute> {
  Conversation _conversation;
  UsersList _membersInfo;
  bool _error = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loadConversation();
  }

  void setError(bool e) => setState(() {
        _error = e;
      });

  /// Load information about the being updated conversation
  Future<void> _loadConversation() async {
    setError(false);

    final conversation = await ConversationsHelper()
        .getSingle(widget.conversationID, force: true);

    if (conversation == null) return setError(true);

    //Load information about the members of the conversation
    _membersInfo = await UsersHelper().getUsersInfo(conversation.members);

    if (_membersInfo == null) return setError(true);

    setState(() {
      _conversation = conversation;
    });
  }

  /// Build the body of this widget
  Widget _buildBody() {
    if (_error)
      return buildErrorCard(
          tr("Could not load information about the conversation"),
          actions: [
            FlatButton(
              onPressed: _loadConversation,
              child: Text(
                tr("Retry").toUpperCase(),
                style: TextStyle(color: Colors.white),
              ),
            )
          ]);

    if (_conversation == null) return buildLoadingPage();

    return UpdateConversationScreen(
      initialUsers: _membersInfo,
      initialSettings: _conversation,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: ComunicBackButton(),
        title: Text(tr("Update a conversation")),
      ),
      body: _buildBody(),
    );
  }
}