2021-04-10 03:04:23 +00:00
|
|
|
import 'dart:async';
|
|
|
|
|
|
|
|
import 'package:equatable/equatable.dart';
|
2024-01-31 05:14:23 +00:00
|
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
2021-04-10 03:04:23 +00:00
|
|
|
import 'package:selfprivacy/logic/common_enum/common_enum.dart';
|
2022-11-12 17:29:06 +00:00
|
|
|
import 'package:selfprivacy/logic/cubit/metrics/metrics_repository.dart';
|
2024-01-31 05:14:23 +00:00
|
|
|
import 'package:selfprivacy/logic/models/metrics.dart';
|
2021-04-10 03:04:23 +00:00
|
|
|
|
2022-11-12 17:29:06 +00:00
|
|
|
part 'metrics_state.dart';
|
2021-04-10 03:04:23 +00:00
|
|
|
|
2022-11-12 17:29:06 +00:00
|
|
|
class MetricsCubit extends Cubit<MetricsState> {
|
|
|
|
MetricsCubit() : super(const MetricsLoading(Period.day));
|
2021-04-10 03:04:23 +00:00
|
|
|
|
2022-11-12 17:29:06 +00:00
|
|
|
final MetricsRepository repository = MetricsRepository();
|
2021-04-10 03:04:23 +00:00
|
|
|
|
|
|
|
Timer? timer;
|
|
|
|
|
2022-05-24 18:55:39 +00:00
|
|
|
@override
|
2022-06-05 19:36:32 +00:00
|
|
|
Future<void> close() {
|
2021-04-10 03:04:23 +00:00
|
|
|
closeTimer();
|
|
|
|
return super.close();
|
|
|
|
}
|
|
|
|
|
|
|
|
void closeTimer() {
|
|
|
|
if (timer != null && timer!.isActive) {
|
|
|
|
timer!.cancel();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-05 19:36:32 +00:00
|
|
|
void changePeriod(final Period period) async {
|
2021-04-10 03:04:23 +00:00
|
|
|
closeTimer();
|
2022-11-12 17:29:06 +00:00
|
|
|
emit(MetricsLoading(period));
|
2021-04-10 03:04:23 +00:00
|
|
|
load(period);
|
|
|
|
}
|
|
|
|
|
|
|
|
void restart() async {
|
|
|
|
load(state.period);
|
|
|
|
}
|
|
|
|
|
2022-06-05 19:36:32 +00:00
|
|
|
void load(final Period period) async {
|
2022-09-09 14:58:01 +00:00
|
|
|
try {
|
2024-08-02 14:37:00 +00:00
|
|
|
final MetricsStateUpdate newStateUpdate =
|
|
|
|
await repository.getRelevantServerMetrics(period);
|
|
|
|
|
|
|
|
int duration = newStateUpdate.nextCheckInSeconds;
|
|
|
|
if (duration <= 0) {
|
|
|
|
duration = state.period.stepPeriodInSeconds;
|
|
|
|
}
|
2022-09-16 08:07:37 +00:00
|
|
|
timer = Timer(
|
2024-08-02 14:37:00 +00:00
|
|
|
Duration(seconds: duration),
|
|
|
|
() => load(period),
|
2022-09-16 08:07:37 +00:00
|
|
|
);
|
2024-08-02 14:37:00 +00:00
|
|
|
|
|
|
|
emit(newStateUpdate.newState);
|
2022-09-09 14:58:01 +00:00
|
|
|
} on StateError {
|
2022-11-12 17:29:06 +00:00
|
|
|
print('Tried to emit metrics when cubit is closed');
|
2022-09-09 14:58:01 +00:00
|
|
|
}
|
2021-04-10 03:04:23 +00:00
|
|
|
}
|
|
|
|
}
|