<script setup lang="ts">
import {
  useCourseDataWithCompletion,
  useCourseSessionDetailQuery,
} from "@/composables";
import { useCockpitStore } from "@/stores/cockpit";
import * as log from "loglevel";
import { onMounted, ref } from "vue";

log.debug("CockpitParentPage created");

const props = defineProps<{
  courseSlug: string;
}>();

const cockpitStore = useCockpitStore();
const courseSessionDetailResult = useCourseSessionDetailQuery();

const loaded = ref(false);

onMounted(async () => {
  log.debug("CockpitParentPage mounted", props.courseSlug);

  try {
    await courseSessionDetailResult.waitForData();
    await cockpitStore.loadCircles(
      props.courseSlug,
      courseSessionDetailResult.findCurrentUser()
    );

    // workaround so that the completion data is loaded before display
    const userDataPromises = courseSessionDetailResult.filterMembers().map((m) => {
      const completionData = useCourseDataWithCompletion(props.courseSlug, m.id);
      return completionData.resultPromise;
    });
    await Promise.all(userDataPromises);

    loaded.value = true;
  } catch (error) {
    log.error(error);
  }
});
</script>

<template>
  <div class="bg-gray-200">
    <main>
      <div v-if="loaded">
        <router-view></router-view>
      </div>
    </main>
  </div>
</template>

<style scoped></style>
