import { createFeatureSelector, createSelector } from '@ngrx/store';
import { RoomsState } from './rooms.reducer';

export const selectRoomsState = createFeatureSelector<RoomsState>('rooms');
export const selectCurrentRoom = createSelector(
  selectRoomsState,
  (state) => state.currentRoom
);
export const selectRoomSettings = createSelector(
  selectRoomsState,
  (state) => state.roomSettings
);
export const selectSearchResults = createSelector(
  selectRoomsState,
  (state) => state.searchResults
);
export const selectIsSearching = createSelector(
  selectRoomsState,
  (state) => state.isSearching
);
export const selectIsConnecting = createSelector(
  selectRoomsState,
  (state) => state.isConnecting
);
export const selectIsConnected = createSelector(
  selectRoomsState,
  (state) => state.isConnected
);
export const selectIsSignalServerReconnecting = createSelector(
  selectRoomsState,
  (state) => state.isSignalServerReconnecting
);
export const selectSignalServerCompatibilityError = createSelector(
  selectRoomsState,
  (state) => state.signalServerCompatibilityError
);
export const selectRoomsError = createSelector(
  selectRoomsState,
  (state) => state.error
);
export const selectCurrentRoomId = createSelector(
  selectCurrentRoom,
  (room) => room?.id ?? null
);
export const selectCurrentRoomName = createSelector(
  selectCurrentRoom,
  (room) => room?.name ?? ''
);
export const selectIsCurrentUserHost = createSelector(
  selectCurrentRoom,
  (room) => room?.hostId
);
export const selectSavedRooms = createSelector(
  selectRoomsState,
  (state) => state.savedRooms
);
export const selectRoomsLoading = createSelector(
  selectRoomsState,
  (state) => state.loading
);
export const selectActiveChannelId = createSelector(
  selectRoomsState,
  (state) => state.activeChannelId
);
export const selectCurrentRoomChannels = createSelector(
  selectCurrentRoom,
  (room) => room?.channels ?? []
);
export const selectTextChannels = createSelector(
  selectCurrentRoomChannels,
  (channels) => channels
    .filter((channel) => channel.type === 'text')
    .sort((channelA, channelB) => channelA.position - channelB.position)
);
export const selectVoiceChannels = createSelector(
  selectCurrentRoomChannels,
  (channels) => channels
    .filter((channel) => channel.type === 'voice')
    .sort((channelA, channelB) => channelA.position - channelB.position)
);
