<script setup lang="ts">
import { showAlert } from '@/alerts';
import { ClassroomComplianceAPIClient } from '@/api/classroom_compliance';
import { useAuthStore } from '@/stores/auth';
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';

const props = defineProps<{
  classId: string
}>()
const authStore = useAuthStore()
const router = useRouter()
const apiClient = new ClassroomComplianceAPIClient(authStore)

const textContent = ref('')
const working = ref(false)
const lines = computed(() => textContent.value.trim().split('\n').filter(s => s.trim().length > 0))
const studentCount = computed(() => lines.value.length)

async function doImport() {
  working.value = true
  const classIdNumber = parseInt(props.classId, 10)
  for (let i = 0; i < lines.value.length; i++) {
    const line = lines.value[i]
    const student = await apiClient.createStudent(classIdNumber, { name: line, deskNumber: 0, removed: false })
      .handleErrorsWithAlert()
    if (!student) break;
  }
  working.value = false
  await showAlert('Created students!')
  await router.replace(`/classroom-compliance/classes/${classIdNumber}`)
}
</script>
<template>
  <div class="centered-content">
    <h1 class="align-center">Import Students</h1>
    <p>
      Import a large number of students to a class at once by pasting their names in the text box below, with one
      student per line.
    </p>
    <form @submit.prevent="doImport">
      <textarea style="min-width: 300px; min-height: 500px;" v-model="textContent"></textarea>
      <div>
        <span>Detected <span>{{ studentCount }}</span> students in the above text.</span>
      </div>
      <div class="button-bar">
        <button type="submit" :disabled="working">Submit</button>
      </div>
    </form>
  </div>
</template>
