import { eventEmitter, EventType } from '../../../../services/EventEmitter';
import React, { useEffect } from 'react';
import {
  getMicState,
  setMicStateUpdates,
  switchMicState,
} from '../../../../store/currentCall/currentCallSlice';
import { MicButtonView } from './MicButtonView';
import { Logger } from '../../../../utils/Log';
import { IImageButtonStyleProps, IStyledProps } from '../../../common/types';
import { ImageSourcePropType } from 'react-native';
import { ImageButton } from '../../../common/ImageButton';
import { useAppDispatch, useAppSelector } from '../../../../store/hooks';

const logger = new Logger('MicButtonContainer');

interface IMicBtnProps extends IStyledProps<IImageButtonStyleProps> {
  mutedImageSource?: ImageSourcePropType;
  unmutedImageSource?: ImageSourcePropType;
  renderOnPress?: () => void;
}

export const MicButton: React.FunctionComponent<IMicBtnProps> = ({ mutedImageSource, unmutedImageSource, renderOnPress, style }) => {
const dispatch = useAppDispatch();
const isMuted = useAppSelector((state) => state.currentCall.isMuted);
  useEffect(() => {
    dispatch(getMicState());
    const handleMicStateUpdatedEvent = (isMicMuted: boolean) => {
      logger.info(`handleMicStateUpdatedEvent: ${isMicMuted}`);
     dispatch(setMicStateUpdates(isMicMuted));
    }
    const micStateUpdatedListener = eventEmitter.addListener(EventType.MicStateUpdated, handleMicStateUpdatedEvent);
    return () => {
      micStateUpdatedListener.remove();
    }
  }, [isMuted]);

  const handleOnPressed = () => {
    if (renderOnPress) {
      renderOnPress();
    }
    else {
      logger.info(`handleOnPressed: is muted ${isMuted}`)
      dispatch(switchMicState());
    }
  }

  if (mutedImageSource && unmutedImageSource) {
    return isMuted ? <ImageButton imageSource={mutedImageSource} onPress={handleOnPressed} style={style} /> : <ImageButton imageSource={unmutedImageSource} onPress={handleOnPressed} style={style} />
  } else {
    return <MicButtonView isMuted={isMuted} onPress={handleOnPressed} style={style} />;
  }
}