import 'package:cross_file/cross_file.dart';
import 'package:dio/dio.dart';
import 'package:hoshan/core/services/api/dio_service.dart';
import 'package:hoshan/data/model/forum_model.dart';

class ForumRepository {
  static final DioService _dioService = DioService();

  static Future<ForumModel> getForumComments(
      {required int categoryId, int? page, String? orderBy}) async {
    try {
      Map<String, dynamic>? queryParameters = {'category_id': categoryId};
      if (page != null) {
        queryParameters['page'] = page;
      }
      if (orderBy != null) {
        queryParameters['order_by'] = orderBy;
      }
      Response response = await _dioService
          .sendRequest()
          .get(DioService.forumComments, queryParameters: queryParameters);
      return ForumModel.fromJson(response.data);
    } catch (ex) {
      rethrow;
    }
  }

  static Future<ForumModel> getForumCommentsReplies(
      {required int categoryId, required int id, int? page}) async {
    try {
      Map<String, dynamic>? queryParameters = {'category_id': categoryId};
      if (page != null) {
        queryParameters['page'] = page;
      }
      Response response = await _dioService.sendRequest().get(
          DioService.forumReplieComments(id),
          queryParameters: queryParameters);
      return ForumModel.fromJson(response.data);
    } catch (ex) {
      rethrow;
    }
  }

  static Future<Comment> sendForum({
    required String text,
    required int categoryId,
    XFile? image,
    int? parentId,
    String? repliedUserId,
  }) async {
    try {
      FormData formDatBody = FormData();

      formDatBody.fields.add(MapEntry('text', text));
      formDatBody.fields.add(MapEntry('category_id', categoryId.toString()));
      if (parentId != null) {
        formDatBody.fields.add(MapEntry('parent_id', parentId.toString()));
      }
      if (repliedUserId != null) {
        formDatBody.fields
            .add(MapEntry('replied_user_id', repliedUserId.toString()));
      }

      if (image != null) {
        MultipartFile multipartFile = await DioService.getMultipartFile(image);
        String nameFileField = 'image';
        formDatBody.files.add(MapEntry(nameFileField, multipartFile));
      }

      Response response = await _dioService
          .sendRequest()
          .post(DioService.forumComments, data: formDatBody);
      return Comment.fromJson(response.data['comment']);
    } catch (ex) {
      rethrow;
    }
  }

  static Future<Response> likedMessage(
      {required final int id, required final int status}) async {
    try {
      final response = await _dioService
          .sendRequest()
          .put(DioService.forumCommentsFeedback(id), data: {"status": status});
      return response;
    } catch (ex) {
      rethrow;
    }
  }
}
