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,
}

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
      }
    },
  },
})

export const { setSelectedMediaDevice } = 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
  }
}

export default mediaDeviceSlice.reducer
