import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:peasmartcare/models/news_model.dart';
import 'package:peasmartcare/models/result_data_model.dart';
import 'package:peasmartcare/services/news_service.dart';
import 'package:peasmartcare/utils/clear_count_notification_util.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'news_list_event.dart';
part 'news_list_state.dart';

class NewsListBloc extends Bloc<NewsListEvent, NewsListState> {
  NewsImpService service = NewsImpService();
  ResultData resultData;

  NewsListBloc() : super(NewsListInitial());

  @override
  Stream<NewsListState> mapEventToState(NewsListEvent event) async* {
    try {
      if (event is NewsListGetList) {
        yield NewsListLoading();
        await ClearCountNotificationUtil.news();

        resultData = await service.getList(authenKey: ShareDataUtil.getAuthenKey());

        List<NewsModel> activityList = resultData.result;

        if (resultData.statusCode == 401) {
          yield NewsListErrorUnauthorized();
        } else {
          yield NewsListLoaded(result: activityList, deleteSuccess: null);
        }
      } else if (event is NewsListOnDelete) {
        await Future.delayed(Duration(seconds: 2));

        List<NewsModel> activityList = resultData.result;

        if (resultData.statusCode == 401) {
          yield NewsListErrorUnauthorized();
        } else {
          yield NewsListLoaded(result: activityList, deleteSuccess: true);
        }
      }
    } catch (e) {
      yield NewsListError(message: "Error");
    }
  }
}
