import '../../about/external/data/Commitment.dart';
import '../../about/external/data/Goal.dart';
import '../../about/external/initial/CompletionRequest.dart';
import '../../about/external/initial/IdRequest.dart';
import '../../utils/ObjectConvertors.dart';
import '../parent/ParentViewModel.dart';
import 'ConnectGoalDetail.dart';

class ViewGoalDetail extends ParentViewModel {
  ConnectGoalDetail connection;

  ViewGoalDetail(super.context, this.connection);

  void loadTasks(Goal goal) async {
    if (!await hasNetwork(() => loadTasks(goal))) return;

    showLoading("Loading ${goal.title}");

    try {
      final response =
          await getDataManager().getGoalTasks(IdRequest(id: goal.id ?? ""));

      closeLoading();

      connection.onGoalLoaded(goal, getCommitmentList(response.data));
    } catch (e) {
      handleError(e, () => loadTasks(goal), () => dismissError(), "Retry");
    }
  }

  /// Completes a task straight from the goal list.
  void tick(Commitment task) async {
    if (!await hasNetwork(() => tick(task))) return;

    try {
      await getDataManager().completeCommitmentEntry(CompletionRequest(
        commitmentId: task.id ?? "",
        proofType: task.proofType.name,
      ));

      connection.onTaskTicked(task, task.wouldBeLate);
    } catch (e) {
      connection.onTickFailed(task);
      handleError(e, () => tick(task), () => dismissError(), "Retry");
    }
  }

  /// Stashes the task as the active one before the runner opens, so the
  /// ongoing notification and any relaunch land back on the right thing.
  void startTask(Commitment task) async {
    await getDataManager().setActiveCommitment(task);

    connection.onTaskReady(task);
  }
}
