import 'package:flutter/material.dart';

import '../../../api/marianumcloud/talk/room/getRoomResponse.dart';
import 'components/chatTile.dart';

class SearchChat extends SearchDelegate {
  List<GetRoomResponseObject> chats;

  SearchChat(this.chats);

  @override
  List<Widget>? buildActions(BuildContext context) => [
      if(query.isNotEmpty) IconButton(onPressed: () => query = '', icon: const Icon(Icons.delete)),
    ];

  @override
  Widget? buildLeading(BuildContext context) => null;

  @override
  Widget buildResults(BuildContext context) {
    var items = chats.where(
            (e) => e.displayName.toString().toLowerCase().contains(query.toLowerCase()) || e.name.toString().toLowerCase().contains(query.toLowerCase())
    ).toList()..sort((a, b) => b.lastActivity.compareTo(a.lastActivity));
    return ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, index) {
        var item = items.elementAt(index);
        return ChatTile(data: item, disableContextActions: true, query: ({bool renew = true}) {});
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) => buildResults(context);
}
