import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { RootState } from '../../app/store'
import { MediaDeviceModel } from './models'
import { SelectMediaDeviceAction } from './actionModels'

const initialState: MediaDeviceModel = {
  selectedAudioDeviceId: null,
  selectedVideoDeviceId: null,
  selectedAudioOutputDeviceId: null,
  videoIsLoading: false,
}

export const mediaDeviceSlice = createSlice({
  name: 'mediaDevice',
  initialState,
  reducers: {
    setSelectedMediaDevice: (state, action: PayloadAction<SelectMediaDeviceAction>) => {
      const { kind, deviceId } = action.payload
      if (kind === 'audioinput') {
        state.selectedAudioDeviceId = deviceId
      } else if (kind === 'videoinput') {
        state.selectedVideoDeviceId = deviceId
      } else if (kind === 'audiooutput') {
        state.selectedAudioOutputDeviceId = deviceId
      }
    },
    setVideoIsLoading: (state, action: PayloadAction<boolean>) => {
      state.videoIsLoading = action.payload
    },
  },
})

export const { setSelectedMediaDevice, setVideoIsLoading } = mediaDeviceSlice.actions

export const selectCurrentAudioDeviceId = (state: RootState) => state.mediaDevice.selectedAudioDeviceId

export const selectCurrentVideoDeviceId = (state: RootState) => state.mediaDevice.selectedVideoDeviceId

export const selectCurrentMediaDeviceId = (state: RootState, kind: MediaDeviceKind) => {
  if (kind === 'audioinput') {
    return state.mediaDevice.selectedAudioDeviceId
  } else if (kind === 'videoinput') {
    return state.mediaDevice.selectedVideoDeviceId
  } else if (kind === 'audiooutput') {
    return state.mediaDevice.selectedAudioOutputDeviceId
  }
}

export const selectVideoIsLoading = (state: RootState) => state.mediaDevice.videoIsLoading

export default mediaDeviceSlice.reducer
