import { ref, computed, watch } from '@vue/composition-api' import { StopwatchState } from '@/types/StopwatchState' import { notify } from '@/utils/notification' import { useInterval } from './useInterval' const format = (num: number) => { return num.toString().padStart(2, '0') } const formatSeconds = (seconds: number) => { const minutes = Math.floor(seconds / 60) const secs = seconds % 60 return `${format(minutes)}:${format(secs)}` } export const useTimer = () => { const timeState = ref('stopped') const seconds = ref(0) const { interval } = useInterval() const sessionSeconds = ref(interval.value * 60) const isDev1Turn = ref(true) const time = computed(() => formatSeconds(seconds.value)) const session = computed(() => formatSeconds(sessionSeconds.value)) const intervalSeconds = computed(() => interval.value * 60) let stopwatchId: number | null = null let stopWatchSessionId: number | null = null watch(interval, () => { sessionSeconds.value = interval.value * 60 }) const start = () => { timeState.value = 'started' stopwatchId = setInterval(() => { seconds.value++ const isTimeToChange = seconds.value % intervalSeconds.value === 0 if (isTimeToChange) { sessionSeconds.value = intervalSeconds.value isDev1Turn.value = !isDev1Turn.value const dev = isDev1Turn.value ? 'Dev 1' : 'Dev 2' notify('Change!', { body: `${dev}, your turn!` }) } }, 1000) stopWatchSessionId = setInterval(() => { sessionSeconds.value-- }, 1000) } const pause = () => { timeState.value = 'stopped' if (stopwatchId) { clearInterval(stopwatchId) stopwatchId = null } if (stopWatchSessionId) { clearInterval(stopWatchSessionId) stopWatchSessionId = null } } const clear = () => { pause() seconds.value = 0 sessionSeconds.value = intervalSeconds.value isDev1Turn.value = true } return { interval, start, pause, clear, timeState, time, session, isDev1Turn } }