import '../../about/external/data/pages/request/HistoryRequest.dart';
import '../../about/external/data/pages/request/PageAndSort.dart';
import '../../about/external/data/pages/request/Pageable.dart';
import '../../about/external/data/pages/request/Sort.dart';
import '../../about/external/initial/GoalRequest.dart';
import '../../utils/ObjectConvertors.dart';
import '../parent/ParentViewModel.dart';
import 'ConnectGoals.dart';

class ViewGoals extends ParentViewModel {
  ConnectGoals connection;

  ViewGoals(super.context, this.connection);

  void loadGoals() async {
    if (!await hasNetwork(() => loadGoals())) return;

    showLoading("Loading your goals");

    try {
      final response = await getDataManager().getMyGoals(HistoryRequest(
        query: PageAndSort(
          sort: Sort('desc', 'startDate'),
          page: Pageable(0, 0, 50, 0),
        ),
      ));

      closeLoading();

      connection.onGoalsLoaded(getGoalList(response.data));
    } catch (e) {
      handleError(e, () => loadGoals(), () => dismissError(), "Retry");
    }
  }

  void save(GoalRequest request) async {
    if (!await hasNetwork(() => save(request))) return;

    showLoading("Saving");

    try {
      await getDataManager().saveGoalEntry(request);

      closeLoading();

      connection.onGoalSaved();
    } catch (e) {
      handleError(e, () => save(request), () => dismissError(), "Retry");
    }
  }
}
