import 'dart:async';

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

part 'select_electricity_location_save_event.dart';
part 'select_electricity_location_save_state.dart';

class SelectElectricityLocationSaveBloc extends Bloc<SelectElectricityLocationSaveEvent, SelectElectricityLocationSaveState> {
  ElectricityLocationImpService service = ElectricityLocationImpService();

  ResultData resultData;

  SelectElectricityLocationSaveBloc() : super(SelectElectricityLocationSaveInitial());

  @override
  Stream<SelectElectricityLocationSaveState> mapEventToState(SelectElectricityLocationSaveEvent event) async* {
    try {
      if (event is SelectElectricityLocationSaveOnSubmit) {
        yield SelectElectricityLocationSaveLoading();

        String caNumber = event.caNumber;
        String peaNumber = event.peaNumber;

        UserModel user = ShareDataUtil.getUserInfo();

        resultData = await service.customerCaCheck(
          caNumber: caNumber,
          peaNumber: peaNumber,
          userId: user.id,
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        CustomerCACheckModel customerCa = resultData.result;

        if (resultData.statusCode == 401) {
          yield SelectElectricityLocationSaveErrorUnauthorized();
        } else {
          if (resultData.statusCode == 200 && resultData != null) {
            ResultData customerContactResultData = await service.createCustomerContact(
              customerId: customerCa.customerId,
              firstname: user.firstname,
              lastname: user.lastname,
              idCard: user.idCard,
              phone: user.phone,
              authenKey: ShareDataUtil.getAuthenKey(),
            );
            bool isSuccess = customerContactResultData.result;

            // yield SelectElectricityLocationSaveLoaded(isSuccess: isSuccess, errorMessage: customerContactResultData.statusMessage);
            yield SelectElectricityLocationSaveLoaded(isSuccess: isSuccess, errorMessage: "หมายเลขผู้ใช้ไฟฟ้า หรือรหัสเครื่องวัดไฟฟ้าไม่ถูกต้อง กรุณากรอกใหม่อีกครัง");
          } else {
            yield SelectElectricityLocationSaveLoaded(isSuccess: false);
          }
        }
      }
    } catch (e) {
      yield SelectElectricityLocationSaveError(message: "เกิดข้อผิดพลาด");
    }
  }
}
