import '../../api/apiResponse.dart';
import '../../api/marianumcloud/talk/chat/getChatCache.dart';
import '../../api/marianumcloud/talk/chat/getChatResponse.dart';
import '../dataHolder.dart';

class ChatProps extends DataHolder {
  String _queryToken = "";
  DateTime _lastTokenSet = DateTime.now();

  GetChatResponse? _getChatResponse;
  GetChatResponse get getChatResponse => _getChatResponse!;

  @override
  List<ApiResponse?> properties() {
    return [_getChatResponse];
  }

  @override
  void run() {
    notifyListeners();
    if(_queryToken.isEmpty) return;
    DateTime requestStart = DateTime.now();

    GetChatCache(
      chatToken: _queryToken,
      onUpdate: (GetChatResponse data) {
        if(_lastTokenSet.isAfter(requestStart)) return; // Another request was faster

        _getChatResponse = data;
        notifyListeners();
      }
    );
  }

  void setQueryToken(String token) {
    _queryToken = token;
    _getChatResponse = null;
    _lastTokenSet = DateTime.now();
    run();
  }

  String currentToken() {
    return _queryToken;
  }
}