import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { RootState } from '../../app/store'
import { ParticipantTranscriptModel, SessionTranscriptModel } from './models'
import {
  RemoveParticipantTranscriptionAction,
  TranscriptionEnableAction,
  TranscriptionReceivedAction,
} from './actionModels'
import { TranscriptionResult } from '@zocks-communications/client-sdk-js'

const initialState: SessionTranscriptModel = {
  status: {
    serviceEnabled: false,
    serviceLoading: false,
    autoEnabled: false,
    displayTranscriptions: false,
    transcriptionInProgress: false,
  },
  transcripts: {},
}

export const transcriptSlice = createSlice({
  name: 'transcript',
  initialState,
  reducers: {
    transcriptionReceived: (state, action: PayloadAction<TranscriptionReceivedAction>) => {
      const { participantId, transcriptionResult } = action.payload
      if (!state.transcripts[participantId]) {
        state.transcripts[participantId] = { finalTranscripts: [], partialTranscript: null }
      }
      const participantTranscripts = state.transcripts[participantId]
      if (transcriptionResult.isFinal) {
        participantTranscripts.finalTranscripts.push(transcriptionResult)
        participantTranscripts.partialTranscript = null
      } else {
        participantTranscripts.partialTranscript = transcriptionResult
      }
    },
    setTranscriptionServiceEnabled: (state, action: PayloadAction<TranscriptionEnableAction>) => {
      const { enabled, autoEnable } = action.payload
      state.status.serviceEnabled = enabled
      if (enabled) {
        state.status.autoEnabled = !!autoEnable
      }
    },
    setTranscriptionServiceIsLoading: (state, action: PayloadAction<boolean>) => {
      state.status.serviceLoading = action.payload
    },
    setDisplayTranscriptions: (state, action: PayloadAction<boolean>) => {
      state.status.displayTranscriptions = action.payload
    },
    setTranscriptionInProgress: (state, action: PayloadAction<boolean>) => {
      const inProgress = action.payload
      state.status.transcriptionInProgress = inProgress
      if (!inProgress) {
        for (const transcript of Object.values(state.transcripts)) {
          transcript.partialTranscript = null
        }
      }
    },
    clearTranscription: (state) => {
      state.transcripts = {}
      state.status.serviceEnabled = false
      state.status.autoEnabled = false
    },
    clearRemoteParticipantTranscription: (state, action: PayloadAction<RemoveParticipantTranscriptionAction>) => {
      const { participantId } = action.payload
      delete state.transcripts[participantId]
    },
  },
})

export const {
  clearRemoteParticipantTranscription,
  clearTranscription,
  setDisplayTranscriptions,
  setTranscriptionServiceEnabled,
  setTranscriptionServiceIsLoading,
  setTranscriptionInProgress,
  transcriptionReceived,
} = transcriptSlice.actions

export const selectTranscriptionStatus = (state: RootState) => state.transcript.status
export const selectTranscripts = (state: RootState) => state.transcript.transcripts

export const selectParticipantTranscripts = (
  state: RootState,
  participantId: string,
  since: number = 0
): ParticipantTranscriptModel => {
  const { transcripts } = state.transcript
  if (!transcripts[participantId]) {
    return { finalTranscripts: [], partialTranscript: null }
  }
  const participantTranscripts = transcripts[participantId]
  return since ? getTranscriptsSince(participantTranscripts, since) : participantTranscripts
}

const getTranscriptsSince = (transcripts: ParticipantTranscriptModel, since: number): ParticipantTranscriptModel => {
  const now = Date.now()
  const finalTranscripts = transcripts.finalTranscripts.filter((t) => transcriptCreatedSince(t, now, since))
  const partialTranscript =
    transcripts.partialTranscript && transcriptCreatedSince(transcripts.partialTranscript, now, since)
      ? transcripts.partialTranscript
      : null
  return {
    partialTranscript,
    finalTranscripts,
  }
}

const transcriptCreatedSince = (transcript: TranscriptionResult, now: number, since: number): boolean => {
  const createdAt = new Date(transcript.createdAt).getTime()
  const difference = (now - createdAt) / 1000
  return difference < since
}

export default transcriptSlice.reducer
