import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:peasmartcare/models/report_incident_type_model.dart';
import 'package:peasmartcare/models/result_data_model.dart';
import 'package:peasmartcare/models/user_model.dart';
import 'package:peasmartcare/services/report_incident_service.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'report_incident_create_event.dart';
part 'report_incident_create_state.dart';

class ReportIncidentCreateBloc extends Bloc<ReportIncidentCreateEvent, ReportIncidentCreateState> {
  ReportIncidentImpService service = ReportIncidentImpService();

  ResultData resultData;
  List<ReportIncidentTypeModel> reportIncidentTypeList = [];

  ReportIncidentCreateBloc() : super(ReportIncidentCreateInitial());

  @override
  Stream<ReportIncidentCreateState> mapEventToState(ReportIncidentCreateEvent event) async* {
    try {
      if (event is ReportIncidentCreateGetData) {
        resultData = await service.getTypeList(authenKey: ShareDataUtil.getAuthenKey());

        reportIncidentTypeList = resultData.result;
        if (resultData.statusCode == 401) {
          yield ReportIncidentCreateErrorUnauthorized();
        } else {
          yield ReportIncidentCreateLoaded(
            result: null,
            reportIncidentTypeList: reportIncidentTypeList,
            user: ShareDataUtil.getUserInfo(),
          );
        }
      } else if (event is ReportIncidentCreateOnSubmit) {
        UserModel user = ShareDataUtil.getUserInfo();
        String customerId = ShareDataUtil.getCustomerId();
        String customerName = ShareDataUtil.getCustomerName();
        String detail = event.detail;
        String incidentTyprId = event.incidentTyprId;
        String informant = "${user.firstname} ${user.lastname}";
        String authenKey = ShareDataUtil.getAuthenKey();

        ResultData resultData = await service.create(
          customerId: customerId,
          detail: detail,
          incidentTypeId: incidentTyprId,
          informant: informant,
          customerName: customerName,
          authenKey: authenKey,
        );
        if (resultData.statusCode == 401) {
          yield ReportIncidentCreateErrorUnauthorized();
        } else {
          yield ReportIncidentCreateLoaded(
            result: resultData.result,
            reportIncidentTypeList: reportIncidentTypeList,
            user: user,
          );
        }
      }
    } catch (e) {
      yield ReportIncidentCreateError(message: "Error");
    }
  }
}
