import 'dart:convert';

import 'package:electronic_assistant/base/base_response.dart';
import 'package:electronic_assistant/data/api/atmob_api.dart';
import 'package:electronic_assistant/data/api/request/chat_history_request.dart';
import 'package:electronic_assistant/data/api/request/chat_request.dart';
import 'package:electronic_assistant/data/bean/chat_item.dart';
import 'package:electronic_assistant/utils/http_handler.dart';
import 'package:electronic_assistant/utils/sse_parse_util.dart';

import '../api/atmob_stream_api.dart';

class ChatRepository {
  ChatRepository._() {}

  Future<Stream<Message>> streamChat(String chatContent,
      {String? talkId, String? agendaId}) {
    return atmobStreamApi
        .chat(ChatRequest(chatContent, talkId: talkId, agendaId: agendaId))
        .then((response) async {
      List<String>? contentType = response.headers['Content-Type'];
      if (contentType != null) {
        for (var value in contentType) {
          if (value.contains('text/event-stream')) {
            return response.stream;
          } else if (value.contains('application/json')) {
            BaseResponse<String> baseResponse = BaseResponse.fromJson(
                jsonDecode(await response.stream
                    .map((bytes) => utf8.decoder.convert(bytes))
                    .toList()
                    .then((value) => value.join())),
                (json) => json as String);
            throw ServerErrorException(baseResponse.code, baseResponse.message);
          }
        }
      }
      throw Exception('Invalid content type');
    }).then((stream) => SSEParseUtil.parse(stream));
  }

  Future<List<ChatItem>> chatHistory(String? lastId) {
    return atmobApi
        .chatHistory(ChatHistoryRequest(1, 20, lastId))
        .then(HttpHandler.handle(true))
        .then((response) => response.chatItems);
  }
}

final chatRepository = ChatRepository._();
