import { parse } from 'date-fns'
import { IBlock, IExercise, IRating } from './types'
import { TrainingQuery, SubBlockFragment } from '../gql'

/**
 * Takes a block of exercises and calculates the duration in seconds.
 * @param block
 */
export function calculateDuration(block: IBlock): number {
  if (block.duration) return block.duration
  const repetitions = block.repetitions || 1
  const rest = block.rest || 0
  if (block.blocks) {
    const subblockDuration = block.blocks.reduce(
      (accumulator, block) =>
        accumulator + (block.duration || calculateDuration(block)),
      0
    )
    return repetitions * (subblockDuration + rest)
  } else {
    return 0
  }
}

/**
 * Formats a time in seconds into 0:00
 * @param seconds
 */
export function formatTime(seconds: number) {
  return `${Math.floor(seconds / 60)}:${(seconds % 60)
    .toString()
    .padStart(2, '0')}`
}

/**
 * Takes an array of exercises and formats them into
 * 4x Exercise 1 - Exercise 2 - 2x Exercise 3
 * @param exercises
 */
export function printExercises(exercises: IExercise[]) {
  return exercises
    .map(exercise =>
      exercise.repetitions > 1
        ? `${exercise.repetitions}x ${exercise.name}`
        : exercise.name
    )
    .join(' - ')
}

/**
 * Takes an array of rating and calculates the average rating
 * @param ratings
 */
export function calculateRating(ratings: IRating[]) {
  const numberOfRatings = ratings.length
  const sumOfRatings = ratings.reduce(
    (accumulator, rating) => accumulator + rating.value,
    0
  )
  return numberOfRatings ? sumOfRatings / numberOfRatings : '-'
}

export function trainingDBToArray(DBTraining: TrainingQuery['training']) {
  console.log({ DBTraining })
  if (!DBTraining) return undefined
  const { blocks, ...data } = DBTraining
  return { ...data, blocks: blockDBToArray(blocks) }
}

export function trainingArrayToDB() {}

export function blockDBToArray(DBSubBlock?: SubBlockFragment[]) {
  console.log({ DBSubBlock })
  if (!DBSubBlock) return undefined
  return DBSubBlock
}

export function blockArrayToDB() {}

const Weekdays = {
  Monday: 1,
  Tuesday: 2,
  Wednesday: 3,
  Thursday: 4,
  Friday: 5,
  Saturday: 6,
  Sunday: 0
}
type TWeekdays = keyof typeof Weekdays
/**
 * Get the date of the next weekday.
 * @param weekDay Sunday=0, Monday=1, Tuesday=2
 * @param time Format: HH:mm
 */
export function nextTime(weekDay: TWeekdays, time: string) {
  const nextTime = parse(time, 'HH:mm', new Date())
  nextTime.setDate(
    nextTime.getDate() + ((Weekdays[weekDay] + 7 - nextTime.getDay()) % 7)
  )
  return nextTime.toISOString()
}
