import 'dart:async'; import 'package:flutter/material.dart'; import 'package:sendtrain/models/activity_model.dart'; class ActivityTimerModel with ChangeNotifier { int _tickCount = 0; int _currentAction = 0; ActivityModel? _activity; Timer? _periodicTimer; List _actionMap = []; int get tickCount => _tickCount; int get currentAction => _currentAction; ActivityModel? get activity => _activity; Timer? get periodicTimer => _periodicTimer; String get actionType => _actionMap[_currentAction]; void setup(ActivityModel activity) { // if there isn't an activity yet // or we're coming from another activity // setup new timer if (_activity == null || activity.id != _activity?.id) { _periodicTimer?.cancel(); _activity = activity; _currentAction = 0; _actionMap = []; // for now we just do alternating rest/sets // in the future, we'll make this more modifiable for (int i = 0; i < activity.actions[0].activityActionSet.total; i++) { _actionMap.addAll(['Set', 'Rest']); } getValue(); } } void getValue() { if (_actionMap[_currentAction] == "Rest") { _tickCount = _activity!.actions[0].activityActionSet.rest ~/ 1000; } else { _tickCount = _activity!.actions[0].activityActionSet.reps.rest ~/ 1000; } } void pause() { _periodicTimer?.cancel(); notifyListeners(); } void setAction(int actionNum, String type) { // always pause if we're manually taversing if (type == 'manual') { pause(); } _currentAction = actionNum; getValue(); notifyListeners(); } void nextAction(String type) { _currentAction + 1 >= _actionMap.length ? pause() : setAction(_currentAction + 1, type); } bool isActive() { return (_periodicTimer != null && _periodicTimer!.isActive) ? true : false; } void start() { if (_activity != null) { _periodicTimer?.cancel(); _periodicTimer = Timer.periodic(const Duration(seconds: 1), (Timer timer) { if (_tickCount <= 0) { nextAction('automatic'); } else { _tickCount--; } notifyListeners(); }); } } }