import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:hoshan/data/model/ai/ai_response_model.dart';
import 'package:hoshan/data/model/ai/send_message_model.dart';
import 'package:hoshan/data/repository/chatbot_repository.dart';
import 'package:image_picker/image_picker.dart';

part 'media_g_response_state.dart';

class MediaGResponseCubit extends Cubit<MediaGResponseState> {
  MediaGResponseCubit() : super(MediaGResponseInitial());

  void request(SendMessageModel model) async {
    emit(MediaGResponseLoading(file: model.file, query: model.query));
    try {
      AiResponseModel response = AiResponseModel();
      await for (String message in ChatbotRepository.sendMessageTool(model)) {
        late Map<String, dynamic> jsonMap;
        try {
          jsonMap = jsonDecode(message);
        } catch (e) {
          if (kDebugMode) {
            print('Error in Parse: $e');
          }
        }

        final r = AiResponseModel.fromJson(jsonMap)
            .copyWith(humanMessageId: model.messageId);
        response = response.copyWith(
            aiMessageId: r.aiMessageId,
            chatId: r.chatId,
            chatTitle: r.chatTitle,
            content: r.content,
            credit: r.credit,
            detail: r.detail,
            error: r.content?.startsWith('Check failed') ?? r.error,
            freeCredit: r.freeCredit,
            humanMessageId: r.humanMessageId,
            statusCode: r.statusCode);
      }

      emit(MediaGResponseSucess(
          response: response,
          file: model.file,
          query: model.query,
          error: response.error ?? false
              ? 'مشکلی از طرف سرور رخ داده است'
              : null));
    } catch (e) {
      if (kDebugMode) {
        print('Dio Error is: $e');
      }
      emit(MediaGResponseFail());
    }
  }
}
