import 'dart:convert';

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

class NotificationServices {
  Future getNotification() async {
    String? token = await UsersInfo().getToken();
    Uri url = Uri.parse("$baseUrl/homepage/list_notification");
    var response = await http.get(url, headers: headerWithToken(token!));
    if (response.statusCode == 200) {
      var dataUsersQNA = jsonDecode(response.body)['data']['users']['qna'];
      var dataUsersCourses =
          jsonDecode(response.body)['data']['users']['courses'];
      var dataUsersAnnouncement =
          jsonDecode(response.body)['data']['users']['announcement'];
      var dataInstructorQNA =
          jsonDecode(response.body)['data']['instructur']['qna'];
      var dataInstructorCourses =
          jsonDecode(response.body)['data']['instructur']['courses_added'];
      var dataInstructorAnnouncement =
          jsonDecode(response.body)['data']['instructur']['announcement'];
      List<NotificationData> data = [];
      List<NotificationDataAnnouncementUser> dataAnnouncement = [];
      for (var item in dataUsersQNA) {
        data.add(NotificationData.qnaFromJson(item));
      }
      for (var item in dataUsersCourses) {
        data.add(NotificationData.coursesFromJson(item));
      }
      // for (var item in dataUsersAnnouncement) {
      //   data.add(NotificationData.announcementFromJson(item));
      // }
      for (var item in dataInstructorQNA) {
        data.add(NotificationData.qnaFromJson(item));
      }
      for (var item in dataInstructorCourses) {
        data.add(NotificationData.coursesFromJson(item));
      }
      // for (var item in dataInstructorAnnouncement) {
      //   data.add(NotificationData.announcementFromJson(item));
      // }
      return [data, dataAnnouncement];
    } else {
      throw Exception('Data Kursus Teratas Gagal Diambil');
    }
  }

  Future readAllNotification() async {
    String? token = await UsersInfo().getToken();
    Uri url = Uri.parse("$baseUrl/homepage/mark_as_read");
    var response = await http.patch(url, headers: headerWithToken(token));
  }

  Future readNotification(String idRead, String ket) async {
    Uri url =
        Uri.parse("$baseUrl/homepage/read/notification?id=$idRead&ket=$ket");
    // var body = jsonEncode({"id": int.parse(idRead), "ket": ket});
    var response = await http.patch(url);
  }

  Future countNotification() async {
    String? token = await UsersInfo().getToken();
    Uri url = Uri.parse("$baseUrl/homepage/list_notification");
    var response = await http.get(url, headers: headerWithToken(token!));
    return jsonDecode(response.body)['data']['count_is_read'];
  }
}
