import 'dart:async';

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

part 'profile_event.dart';
part 'profile_state.dart';

class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
  ProfileImpService service = ProfileImpService();
  ResultData resultData;
  ResultData profileResultData;

  ProfileBloc() : super(ProfileInitial());

  @override
  Stream<ProfileState> mapEventToState(ProfileEvent event) async* {
    try {
      if (event is ProfileGetData) {
        yield ProfileLoading();

        UserModel user = ShareDataUtil.getUserInfo();
        // profile = ProfileModel();
        // profile.firstname = user.firstname;
        // profile.lastname = user.lastname;
        // profile.idCard = user.idCard;
        // profile.phone = user.phone;

        // String fullname = "${user.firstname} ${user.lastname}";

        profileResultData = await service.getDetail(
          idCard: user.idCard,
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        ProfileModel userProfile = profileResultData.result;
        userProfile.firstname = user.firstname;
        userProfile.lastname = user.lastname;

        if (profileResultData.statusCode == 401) {
          yield ProfileErrorUnauthorized();
        } else {
          yield ProfileLoaded(result: userProfile, saveSuccess: null);
        }
      } else if (event is ProfileOnSubmit) {
        yield ProfileLoading();

        String firstname = event.firstname;
        String lastname = event.lastname;
        String idCard = event.idCard;
        String position = event.position;
        String phone = event.phone;
        String otherContact = event.otherContact;

        resultData = await service.save(
          firstname: firstname,
          lastname: lastname,
          idCard: idCard,
          position: position,
          phone: phone,
          otherContact: otherContact,
          authenKey: ShareDataUtil.getAuthenKey(),
        );
        if (resultData.statusCode == 401) {
          yield ProfileErrorUnauthorized();
        } else {
          yield ProfileLoaded(result: profileResultData.result, saveSuccess: resultData.result);
        }
      }
    } catch (e) {
      yield ProfileError(message: "Error");
    }
  }
}
