import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_chat_ui/flutter_chat_ui.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'dart:math';

import '../basic/Entities.dart';
import '../basic/Method.dart';


String randomString() {
  final random = Random.secure();
  final values = List<int>.generate(16, (i) => random.nextInt(255));
  return base64UrlEncode(values);
}

class ChatScreen extends StatefulWidget {
  const ChatScreen(this.profile, this.roomId, {Key? key}) : super(key: key);

  final Profile profile;
  final String roomId;

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  late List<types.Message> _messages = [];

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

  Future _load() async {
    final ret = await method.getMessages(widget.roomId) ?? [];
    setState(() {
      _messages = ret;
    });
  }

  @override
  Widget build(BuildContext context) => Scaffold(
    body: Chat(
      messages: _messages,
      onSendPressed: _handleSendPressed,
      user: method.user,
    ),
  );

  void _addMessage(types.Message message) {
    setState(() {
      _messages.insert(0, message);
    });
  }

  void _handleSendPressed(types.PartialText message) {
    final textMessage = types.TextMessage(
      author: method.user,
      id: randomString(),
      text: message.text,
    );
    method.sendMessage(widget.roomId, types.MessageType.text, message.text);

    _addMessage(textMessage);
  }
}
