index.jsjavascript
import { musclePriorityList } from './components/templates/musclePriorityList.js'
import { exercisePicker, wireExercisePickerEvents } from './components/templates/exercisePicker.js'
import { lastSessionDisplay, formatLastSession } from './components/templates/lastSessionDisplay.js'
import { logWorkoutForm, wireLogWorkoutFormEvents } from './components/templates/logWorkoutForm.js'
import { addExerciseForm, wireAddExerciseFormEvents } from './components/templates/addExerciseForm.js'
import { getMusclePriority, getExercisesForMuscle, getLastSession } from './data/browserReads.js'

/* global jsonDom, jsonDomComponents -- both loaded as plain scripts in muscles.html before this native ES module runs, not npm imports */
window.jsonDom = jsonDom
const { option, text, main, header, heading } = jsonDomComponents

// Reads run here, on json-fs-query's browser build: it reads database/ from this page's own origin (see
// data/browserReads.js), so the page works with no server running. Writes need real filesystem access, which a page
// never has, so they still go to server/server.js (`npm run serve:api`).
const API_BASE = 'http://localhost:3001'

let picker
let lastSessionItem
let logForm
let addForm
let lastSessionId = null

const fillFormFrom = (session) => {
  logForm.weightEffortInput.element.value = session ? session.weight_effort || '' : ''
  logForm.setsInput.element.value = session ? session.sets : ''
  logForm.repsInput.element.value = session ? session.reps : ''
  logForm.noteInput.element.value = session ? session.note || '' : ''
}

const updateLastSession = (session) => {
  lastSessionId = session ? session._id : null
  fillFormFrom(session)
  lastSessionItem.children = [text(formatLastSession(session))]
  jsonDom.updateChildNodes(lastSessionItem)
}

const onExerciseChange = (exerciseId) => {
  if (!exerciseId) {
    updateLastSession(null)
    return
  }
  getLastSession(exerciseId).then(updateLastSession)
}

const onLogWorkout = ({ weightEffort, sets, reps, note, date }) => {
  const exerciseId = picker.exerciseSelect.element.value
  if (!exerciseId) {
    return
  }
  fetch(`${API_BASE}/api/workouts`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      exerciseId,
      weightEffort,
      sets: sets || 0,
      reps: reps || 0,
      note,
      date
    })
  })
    .then((response) => response.json())
    .then(() => onExerciseChange(exerciseId))
}

const onUpdateWorkout = ({ weightEffort, sets, reps, note }) => {
  if (!lastSessionId) {
    return
  }
  const exerciseId = picker.exerciseSelect.element.value
  fetch(`${API_BASE}/api/workouts/${lastSessionId}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ weightEffort, sets: sets || 0, reps: reps || 0, note })
  })
    .then((response) => response.json())
    .then(() => onExerciseChange(exerciseId))
}

const onAddExercise = ({ name, description, primaryMuscleIds, secondaryMuscleIds }) => {
  if (!name) {
    return
  }
  const muscleAssignments = [
    ...primaryMuscleIds.map((muscleId) => ({ muscleId, rank: 100 })),
    ...secondaryMuscleIds.map((muscleId) => ({ muscleId, rank: 50 }))
  ]
  fetch(`${API_BASE}/api/exercises`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, description, muscleAssignments })
  })
    .then((response) => response.json())
    .then(() => {
      addForm.nameInput.element.value = ''
      addForm.descriptionInput.element.value = ''
      Array.from(addForm.primaryMusclesSelect.element.options).forEach((opt) => { opt.selected = false })
      Array.from(addForm.secondaryMusclesSelect.element.options).forEach((opt) => { opt.selected = false })
      // The new exercise may apply to whichever muscle is currently selected - refresh its list.
      onMuscleChange(picker.muscleSelect.element.value)
    })
}

const onMuscleChange = (muscleId) => {
  getExercisesForMuscle(muscleId)
    .then((exercises) => {
      picker.exerciseSelect.children = exercises.length
        ? exercises.map((exercise) => option(String(exercise._id), exercise.name))
        : [option('', 'No exercises for this muscle yet')]
      picker.exerciseSelect.element.disabled = exercises.length === 0
      jsonDom.updateChildNodes(picker.exerciseSelect)
      if (!exercises.length) {
        updateLastSession(null)
        return
      }
      const firstExerciseId = String(exercises[0]._id)
      picker.exerciseSelect.element.value = firstExerciseId
      onExerciseChange(firstExerciseId)
    })
}

const renderPage = (priorityRows) => {
  const mainHeader = header([heading(1, [text('Workout Planner')])])
  const priorityTable = musclePriorityList(priorityRows)
  picker = exercisePicker(priorityRows)
  lastSessionItem = lastSessionDisplay(null)
  logForm = logWorkoutForm()
  addForm = addExerciseForm(priorityRows)
  const documentItem = jsonDom.documentItem
  jsonDom.updateDomItems(documentItem)

  documentItem.head.children.push(priorityTable.style)

  // Add the header as the first child of body
  documentItem.body.children.unshift(mainHeader)

  const mainContent = main([
    priorityTable.table,
    picker.container,
    lastSessionItem,
    logForm.container,
    addForm.container
  ])

  documentItem.body.children.push(mainContent)

  // Update the body child node list to include the header
  jsonDom.updateChildNodes(documentItem.head)
  // Update the style for the table
  jsonDom.updateElements(priorityTable.style)

  jsonDom.updateChildNodes(documentItem.body)
  // Update the header to generate the elements
  jsonDom.updateElements(mainHeader)
  // Update the table to generate the elements
  jsonDom.updateElements(mainContent)

  // Only now does every new node have both a real element and a complete parentItem chain up to
  // documentItem - fullAddEventListener needs both, so event wiring has to happen after this.
  jsonDom.setParentItemReferences(documentItem)
  wireExercisePickerEvents(picker, onMuscleChange, onExerciseChange)
  wireLogWorkoutFormEvents(logForm, onLogWorkout, onUpdateWorkout)
  wireAddExerciseFormEvents(addForm, onAddExercise)

  if (priorityRows.length) {
    onMuscleChange(String(priorityRows[0].muscleId))
  }
}

getMusclePriority()
  .then(renderPage)
  .catch((error) => {
    console.error('Could not read the muscle priority from database/', error)
    renderPage([])
  })