import { eventEmitter, EventType } from '../../../../services/EventEmitter';
import React, { useEffect } from 'react';
import {
  getSpeakerState,
  setSpeakerStateUpdates,
  switchSpeakerState,
} from '../../../../store/currentCall/currentCallSlice';
import { LoudspeakerButtonView } from './LoudspeakerButtonView';
import { IImageButtonStyleProps, IStyledProps } from '../../../common/types';
import { ImageSourcePropType } from 'react-native';
import { ImageButton } from '../../../common/ImageButton';
import { useAppDispatch, useAppSelector } from '../../../../store/hooks';
export interface ILoudSpeakerProps extends IStyledProps<IImageButtonStyleProps> {
  loudspeakerOnImageSource?: ImageSourcePropType;
  loudspeakerOffImageSource?: ImageSourcePropType;
  renderOnPress?: () => void;
}

export const LoudspeakerButton: React.FunctionComponent<ILoudSpeakerProps> = ({  loudspeakerOffImageSource, loudspeakerOnImageSource, renderOnPress, style }) => {
const dispatch = useAppDispatch();
const isSpeakerOn = useAppSelector((state) => state.currentCall.isSpeakerOn);

  useEffect(() => {
    dispatch(getSpeakerState());
    const handleSpeakerStateUpdatedEvent = (isSpeaker: boolean) => {
      dispatch(setSpeakerStateUpdates(isSpeaker))
    };
    const speakerStateUpdatedListener = eventEmitter.addListener(EventType.SpeakerStateUpdated, handleSpeakerStateUpdatedEvent);

    return () => {
      speakerStateUpdatedListener.remove();
    }
  }, []);

  const handleOnPressed = () => {
    if (renderOnPress) {
      renderOnPress();
    }
    else {
      dispatch(switchSpeakerState());
    }
  }

  if (loudspeakerOffImageSource && loudspeakerOnImageSource) {
    return isSpeakerOn ? <ImageButton imageSource={loudspeakerOnImageSource} onPress={handleOnPressed} style={style} />
      : <ImageButton imageSource={loudspeakerOffImageSource} onPress={handleOnPressed} style={style} />
  } else {
    return <LoudspeakerButtonView onPress={handleOnPressed} isLoudspeakerOn={isSpeakerOn} style={style} />
  }
}