import 'dart:async';

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

part 'additional_service_history_event.dart';
part 'additional_service_history_state.dart';

class AdditionalServiceHistoryBloc extends Bloc<AdditionalServiceHistoryEvent, AdditionalServiceHistoryState> {
  AdditionalImpService service = AdditionalImpService();

  ResultData resultData;

  AdditionalServiceHistoryBloc() : super(AdditionalServiceHistoryInitial());

  @override
  Stream<AdditionalServiceHistoryState> mapEventToState(AdditionalServiceHistoryEvent event) async* {
    try {
      if (event is AdditionalServiceHistoryGetList) {
        yield AdditionalServiceHistoryLoading();

        resultData = await service.getHistoryList(
          caNumber: ShareDataUtil.getCaNumber(),
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        if (resultData.statusCode == 401) {
          yield AdditionalServiceHistoryErrorUnauthorized();
        } else {
          yield AdditionalServiceHistoryLoaded(
            result: resultData.result,
            deleteSuccess: null,
          );
        }
      } else if (event is AdditionalServiceHistoryOnDelete) {
        yield AdditionalServiceHistoryLoading();
        UserModel user = ShareDataUtil.getUserInfo();
        String id = event.id;
        String caNumber = ShareDataUtil.getCaNumber();
        String statusId = "1";
        String createBy = user.firstname;
        String descreption = "ลบบริการเสริม";
        await Future.delayed(Duration(seconds: 1));
        ResultData deleteResult = await service.delete(
          id: id,
          caNumber: caNumber,
          statusId: statusId,
          createBy: createBy,
          descreption: descreption,
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        if (resultData.statusCode == 401) {
          yield AdditionalServiceHistoryErrorUnauthorized();
        } else {
          yield AdditionalServiceHistoryLoaded(
            result: resultData.result,
            deleteSuccess: deleteResult.result,
          );
        }
      }
    } catch (e) {
      yield AdditionalServiceHistoryError(message: "Error");
    }
  }
}
