import React, { useEffect, useState } from 'react';
import { Image, ImageStyle } from 'react-native';
import forwardOff from '../../resources/images/forwardOff.png';
import forwardPhonenumber from '../../resources/images/forwardPhonenumber.png';
import forwardVoicemail from '../../resources/images/forwardVoicemail.png';
import mobileRinging from '../../resources/images/mobileRinging.png';
import mobileRingingOff from '../../resources/images/mobileRingingOff.png';
import { pbxService } from '../../services/calls/pbx';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import { TelephonyStatus } from '../../store/pbx/types';
import { Logger } from '../../utils/Log';
import { IImageButtonStyleProps } from '../common/types';

const logger = new Logger('telephonyContainer');
interface IProps {
  style?: ImageStyle;
}

export const TelephonyIcon: React.FunctionComponent<IProps> = ({ style }) => {
  const [telephonyStatus, setTelephonyStatus] = useState<TelephonyStatus>(
    TelephonyStatus.forward_off
  );

  const handleTelephonyStatusUpdated = (status: TelephonyStatus) => {
    logger.info(`'handleTelephonyStatusUpdated: '${status}`);
    setTelephonyStatus(status);
  };
  useEffect(() => {
    pbxService.getTelephonyStatus();
    const telephonyStatusUpdatedListener = eventEmitter.addListener(
      EventType.TelephonyStatusUpdated,
      handleTelephonyStatusUpdated
    );
    return () => {
      telephonyStatusUpdatedListener.remove();
    };
  });

  const getTelephonyIcon = (status: TelephonyStatus): Element => {
    switch (status) {
      case TelephonyStatus.forward_off:
        return forwardOff;
      case TelephonyStatus.forward_phonenumber:
        return forwardPhonenumber;
      case TelephonyStatus.forward_voicemail:
        return forwardVoicemail;
      case TelephonyStatus.nomadic_activated:
        return mobileRinging;
      case TelephonyStatus.nomadic_dctivated:
        return mobileRingingOff;
    }
  };
  const iconStyle = { ...defaultStyle.image, ...style };
  return <Image style={iconStyle} source={getTelephonyIcon(telephonyStatus)} />;
};
const defaultStyle: IImageButtonStyleProps = {
  image: {
    width: 30,
    height: 30,
  },
};
