import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/models/announcement_model.dart';
import 'package:initial_folder/models/section_model.dart';

class AnnouncementService {
  Future<AnnouncementModel> getAnnouncement(String idCourse) async {
    String? token = await UsersInfo().getToken();
    Uri url = Uri.parse('$baseUrl/users/announcement/$idCourse');

    http.Response response =
        await http.get(url, headers: headerWithToken(token!));

    if (response.statusCode == 200) {
      return AnnouncementModel.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Gagal ambil data');
    }
  }

  Future<bool> replyAnnouncement(
      String tokenAnnouncement, String textBody, String idAnnouncement) async {
    int? userId = await UsersInfo().getIdUser();
    String? token = await UsersInfo().getToken();
    Uri url = Uri.parse('$baseUrl/users/announcement/reply');

    var body = jsonEncode({
      "sender": userId,
      "token": tokenAnnouncement,
      "replies": idAnnouncement,
      "body": textBody,
    });

    http.Response response =
        await http.post(url, headers: headerWithToken(token!), body: body);

    if (response.statusCode == 201) {
      return true;
    } else {
      return false;
    }
  }

  Future<bool> likeAnnouncement(String tokenAnnouncement) async {
    int? userId = await UsersInfo().getIdUser();
    String? token = await UsersInfo().getToken();
    Uri url = Uri.parse('$baseUrl/users/announcement/like');

    var body = jsonEncode({"id_user": userId, "token": tokenAnnouncement});

    http.Response response =
        await http.post(url, headers: headerWithToken(token!), body: body);
    if (response.statusCode == 200) {
      return true;
    } else {
      return false;
    }
  }
}
