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_detail_event.dart';
part 'news_detail_state.dart';

class NewsDetailBloc extends Bloc<NewsDetailEvent, NewsDetailState> {
  NewsImpService service = NewsImpService();
  ResultData resultData;

  NewsDetailBloc() : super(NewsDetailInitial());

  @override
  Stream<NewsDetailState> mapEventToState(NewsDetailEvent event) async* {
    try {
      if (event is NewsDetailGetData) {
        yield NewsDetailLoading();

        await ClearCountNotificationUtil.news();
        String id = event.id;
        resultData = await service.getDetail(id: id, authenKey: ShareDataUtil.getAuthenKey());

        NewsModel news = resultData.result;

        if (resultData.statusCode == 401) {
          yield NewsDetailErrorUnauthorized();
        } else {
          if (news.isActive) {
            yield NewsDetailLoaded(result: news);
          } else {
            yield NewsDetailNotFound();
          }
        }
      }
    } catch (e) {
      yield NewsDetailError(message: "Error");
    }
  }
}
