import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/custom_model/Environment.dart';
import 'package:farm_tpf/custom_model/EnvironmentParameter.dart';
import 'package:farm_tpf/data/api/app_exception.dart';
import 'package:farm_tpf/data/repository/repository.dart';
import 'package:meta/meta.dart';

part 'plot_parameter_event.dart';
part 'plot_parameter_state.dart';

class PlotParameterBloc extends Bloc<PlotParameterEvent, PlotParameterState> {
  final Repository repository;
  PlotParameterBloc({required this.repository}) : super(PlotParameterInitial());
  static int pageSize = 100;
  StreamSubscription? _periodicSubscription;

  @override
  Stream<PlotParameterState> mapEventToState(
    PlotParameterEvent event,
  ) async* {
    if (event is DataFetched) {
      try {
        if (state is PlotParameterInitial) {
          yield PlotParameterLoading();
          final response = await repository.getEnvironmentParameters(cropId: event.cropId, page: 0, size: pageSize);
          var updatedList = <EnvironmentParameter>[];
          response.forEach((element) {
            updatedList.add(EnvironmentParameter.clone(element));
          });
          yield PlotParameterSuccess(items: updatedList, page: 0, hasReachedMax: response.length < pageSize ? true : false);
        }
        if (state is PlotParameterSuccess) {
          if (_periodicSubscription == null) {
            _periodicSubscription ??= Stream.periodic(const Duration(seconds: 5), (x) => x)
                .listen((_) => add(OnRefresh(cropId: event.cropId)), onError: (error) => print("Do something with $error"));
          } else {
            _periodicSubscription!.resume();
          }
        }
      } catch (e) {
        var errorString = AppException.handleError(e);
        yield PlotParameterFailure(errorString: errorString);
      }
    }
    if (event is OnRefresh) {
      try {
        final response = await repository.getEnvironmentParameters(cropId: event.cropId, page: 0, size: pageSize);
        var updatedList = <EnvironmentParameter>[];
        response.forEach((element) {
          updatedList.add(EnvironmentParameter.clone(element));
        });
        yield PlotParameterSuccess(items: response, page: 0, hasReachedMax: response.length < pageSize ? true : false);
      } catch (e) {
        yield PlotParameterFailure(errorString: AppException.handleError(e));
      }
    }
  }

  @override
  Future<void> close() async {
    await _periodicSubscription?.cancel();
    // _periodicSubscription = null;
    return super.close();
  }
}
