
import React, { FunctionComponent } from 'react';
import { RetrieveCallButtonView } from './RetrieveCallButtonView';
import { IStyledProps } from '../../../../common/types';
import { TextStyle, ViewStyle } from 'react-native';
import { alternateCalls, retrieveCall } from '../../../../../store/pbx/pbxSlice';
import { Logger } from '../../../../../utils/Log';
import { CallState } from '../../../../../store/webrtc/types';
import { IPbxCall } from '../../../../../store/pbx/types';
import { useAppDispatch, useAppSelector } from '../../../../../store/hooks';
interface IProps extends IStyledProps<{ icon?: TextStyle, container?: ViewStyle }> {
    call: IPbxCall
    iconCallName?: string
}
const logger = new Logger('RetrieveCallButtonContainer');

export const RetrieveCallButton: FunctionComponent<IProps> = ({ call,  iconCallName, style }) => {
    const dispatch = useAppDispatch();
    const secondCall = useAppSelector((state) => state.pbx.secondCall);
    const sessionsCount = useAppSelector((state) => state.pbx.sessionsCount);
    const executeAlternate = () => {
        if (call.callState === CallState.HELD) {
            logger.info('onRetrieveCall: retrieve the held first call ');
            dispatch(alternateCalls({activeCallId: secondCall!.callReferenceId, heldCallId: call!.callId}));
        } else {
            logger.info('onRetrieveCall: retrieve the second first call ');
            dispatch(alternateCalls({activeCallId: call!.callId, heldCallId: secondCall!.callReferenceId}));
        }
    };
    const onRetrieveCall = () => {
        if (sessionsCount === 1) {
            logger.info('onRetrieveCall: retrieve the single current held call');
            // ** single call : retrieve the current held call
            // ** second call : One of the session is removed : make sure which on of the two sessions to retrieve
            const callToRetrieveId =
                call == null
                    ? secondCall!.callReferenceId
                    : call!.callId;
            retrieveCall(callToRetrieveId);
        } else {
            // We have a second Call , depends on call state you can alternate between them.
            logger.info('onRetrieveCall: two session Added , call executeAlternate');
            executeAlternate();
        }
    };
    return <RetrieveCallButtonView onPress={onRetrieveCall} callIconName={iconCallName} style={style} />;
};