import 'dart:async';

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

part 'electricity_statistic_event.dart';
part 'electricity_statistic_state.dart';

class ElectricityStatisticBloc extends Bloc<ElectricityStatisticEvent, ElectricityStatisticState> {
  ElectricityStatisticImpService service = ElectricityStatisticImpService();

  ResultData resultData;
  ResultData statisticTyperesultData;
  String peaNumber;
  String type;
  String startDate;
  String endDate;

  // List<ElectricityStatisticModel> resultData;

  ElectricityStatisticBloc() : super(ElectricityStatisticInitial());

  @override
  Stream<ElectricityStatisticState> mapEventToState(ElectricityStatisticEvent event) async* {
    try {
      if (event is ElectricityStatisticOnSearch) {
        peaNumber = event.peaNumber;
        type = event.type;
        startDate = event.startDate;
        endDate = event.endDate;

        yield ElectricityStatisticLoading();

        resultData = await service.getStatisticList(
          peaNumber: peaNumber,
          statisticType: type,
          caNumber: ShareDataUtil.getCaNumber(),
          startDate: startDate,
          endDate: endDate,
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        if (resultData.statusCode == 401) {
          yield ElectricityStatisticErrorUnauthorized();
        } else {
          yield ElectricityStatisticLoaded(result: resultData.result);
        }
      } else if (event is ElectricityStatisticClearData) {
        resultData = ResultData();
        resultData.result = null;

        if (resultData.statusCode == 401) {
          yield ElectricityStatisticErrorUnauthorized();
        } else {
          yield ElectricityStatisticLoaded(result: null);
        }
      }
    } catch (e) {
      yield ElectricityStatisticError(message: "หมายเลขผู้ใช้ไฟฟ้า หรือ รหัสเครื่องวัดไฟฟ้า ไม่ถูกต้อง เพื่อให้ผู้ใช้งานรู้ว่ามีข้อผิดพลาด");
    }
  }
}
