import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:initial_folder/models/announcement_model.dart';
import 'package:initial_folder/services/announcement_service.dart';
import 'package:rxdart/rxdart.dart';

enum ResultState { loading, noData, hasData, error }

enum ResultStateLike { loading, error }

class AnnouncementProvider with ChangeNotifier {
  final _service = AnnouncementService();

  StreamController<AnnouncementModel> streamController = BehaviorSubject();
  String _message = '';
  String get message => _message;

  ResultState? _state;
  ResultState? get state => _state;

  AnnouncementModel? _announcementModel;
  AnnouncementModel? get result => _announcementModel;

  set annoucementModel(AnnouncementModel? announcementModel) {
    _announcementModel = announcementModel;
    notifyListeners();
  }

  Stream<AnnouncementModel> get announcementStream {
    return streamController.stream;
  }

  Future<void> getAnnouncement(String id) async {
    try {
      AnnouncementModel announcementModel = await _service.getAnnouncement(id);
      if (announcementModel.error == true && announcementModel.status == 404) {
        // Jika respons adalah 404 (tidak ditemukan), tangani objek dummy di sini
        // Misalnya, menampilkan pesan kepada pengguna bahwa tidak ada data yang ditemukan
        // Atau menampilkan UI yang sesuai
        print('masuk rerror dsiinii');
        streamController.add(announcementModel);
      } else {
        // Jika respons adalah 200 (berhasil), tambahkan data ke dalam stream
        streamController.add(announcementModel);
      }
    } catch (e) {
      throw Error;
    }
  }

  Future<bool> likeAnnouncement(String tokenAnnouncement) async {
    try {
      _state = ResultState.loading;
      notifyListeners();

      bool response =
          await AnnouncementService().likeAnnouncement(tokenAnnouncement);
      if (response) {
        _state = ResultState.hasData;
        notifyListeners();
        return true;
      } else {
        _state = ResultState.noData;
        notifyListeners();
        return false;
      }
    } catch (e) {
      _state = ResultState.error;
      notifyListeners();
      return false;
    }
  }

  Future<bool> replyAnnouncement(String textBody, String idAnnouncmenet,
      String tokenAnnouncement, String idAnnouncement) async {
    try {
      _state = ResultState.loading;
      notifyListeners();

      bool response = await AnnouncementService()
          .replyAnnouncement(tokenAnnouncement, textBody, idAnnouncement);
      if (response) {
        _state = ResultState.hasData;
        notifyListeners();
        return true;
      } else {
        _state = ResultState.noData;
        notifyListeners();
        return false;
      }
    } catch (e) {
      _state = ResultState.error;
      notifyListeners();
      return false;
    }
  }
}
