import 'dart:async';

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

part 'electricity_location_save_event.dart';
part 'electricity_location_save_state.dart';

class ElectricityLocationSaveBloc extends Bloc<ElectricityLocationSaveEvent, ElectricityLocationSaveState> {
  ElectricityLocationImpService service = ElectricityLocationImpService();

  ResultData resultData;

  ElectricityLocationSaveBloc() : super(ElectricityLocationSaveInitial());

  @override
  Stream<ElectricityLocationSaveState> mapEventToState(ElectricityLocationSaveEvent event) async* {
    try {
      if (event is ElectricityLocationSaveOnSubmit) {
        yield ElectricityLocationSaveLoading();

        double latitude = event.latitude;
        double longitude = event.longitude;

        resultData = await service.saveCurrentLocation(
          latitude: latitude,
          longitude: longitude,
          customerId: ShareDataUtil.getCustomerId(),
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        // await Future.delayed(Duration(seconds: 2));

        if (resultData.statusCode == 401) {
          yield ElectricityLocationSaveErrorUnauthorized();
        } else {
          if (resultData.statusCode == 200 && resultData != null && resultData.result) {
            yield ElectricityLocationSaveLoaded(saveSuccess: resultData.result);
          } else {
            yield ElectricityLocationSaveLoaded(saveSuccess: false);
          }
        }
      }
    } catch (e) {
      yield ElectricityLocationSaveError(message: "เกิดข้อผิดพลาด");
    }
  }
}
