import { createAction, createReducer } from '@reduxjs/toolkit';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { MediaStates } from '../store/roomSlice';
import { peerMetadataUpdated, roomJoined, switchToWebinar } from '../store/peersSlice';
import { parseJwt } from '../utils/browser-utils';
import { WebinarAcceptRequestType } from '../types/newTypes';
import { Alert } from 'react-native';
import uuid from 'react-native-uuid';
export var permissionEnum;
(function (permissionEnum) {
    permissionEnum[permissionEnum["ACCEPTED"] = 0] = "ACCEPTED";
    permissionEnum[permissionEnum["DENIED"] = 1] = "DENIED";
    permissionEnum[permissionEnum["FAILED"] = 2] = "FAILED";
    permissionEnum[permissionEnum["INIT"] = 3] = "INIT";
})(permissionEnum || (permissionEnum = {}));
export const setUser = createAction('participant/set-user');
export const setUserToken = createAction('participant/set-token');
export const setLoggedIn = createAction('participant/set-logged-in');
export const setUserDisplayName = createAction('participant/set-display-name');
export const setUserDisplayImageURL = createAction('participant/set-display-image');
export const setVideoProduction = createAction('participant/set-video-production');
export const setAudioProduction = createAction('participant/set-audio-production');
export const setScreenSharingProduction = createAction('participant/set-screen-sharing-production');
export const setAudioMuted = createAction('participant/set-audio-muted');
export const setScreenSharing = createAction('participant/set-screen-sharing');
export const setVideoOff = createAction('participant/set-video-off');
export const setVideoTrackSelection = createAction('participant/set-video-track-selection');
export const setAudioTrackSelection = createAction('participant/set-audio-track-selection');
export const setParticipantPermissions = createAction('participant/set-permissions');
// Webinar Actions
export const requestToJoinStageAccepted = createAction('websocket/request-to-join-stage-accepted');
export const requestToJoinStageRejected = createAction('websocket/request-to-join-stage-rejected');
export const removedFromStage = createAction('websocket/removed-from-stage');
export const requestedJoinToStageState = createAction('room/request-to-join-stage-state');
export const requestToJoinType = createAction('participant/request-to-join-type');
export const startedPresenting = createAction('websocket/started-presenting');
export const stoppedPresenting = createAction('websocket/stopped-presenting');
export const initiatePresenting = createAction('participant/initiate-presenting');
export const requestToJoinPeerStageAccepted = createAction('websocket/peer-added-to-stage');
export const resetParticipant = createAction('session/reset-pariticipant');
export const setCameraFacing = createAction('session/camera-facing');
export const muteAll = createAction('websocket/mute-all');
export const muteAllVideo = createAction('websocket/mute-all-video');
export const disableAudio = createAction('websocket/disable-audio');
export const disableVideo = createAction('websocket/disable-video');
export const setVisibilitySettings = createAction('websocket/visibility-settings');
export const updateCanPresent = createAction('websocket/update_can_update');
export const updateWebinarPresentingSetting = createAction('websocket/update-webinar-update-setting');
// Webinar End
export const updatePreset = createAction('websocket/update-userpreset');
export const switchToGroupCall = createAction('session/switch-group-call');
export var JoinStageSettings;
(function (JoinStageSettings) {
    JoinStageSettings["ALLOWED"] = "allowed";
    JoinStageSettings["ON_REQUEST"] = "on_request";
    JoinStageSettings["NOT_ALLOWED"] = "not_allowed";
})(JoinStageSettings || (JoinStageSettings = {}));
export var PresentingState;
(function (PresentingState) {
    PresentingState[PresentingState["PRESENTING"] = 0] = "PRESENTING";
    PresentingState[PresentingState["NOT_PRESENTING"] = 1] = "NOT_PRESENTING";
    PresentingState[PresentingState["INITIATED"] = 2] = "INITIATED";
})(PresentingState || (PresentingState = {}));
export var RequestToJoinStageState;
(function (RequestToJoinStageState) {
    RequestToJoinStageState[RequestToJoinStageState["NONE"] = 0] = "NONE";
    RequestToJoinStageState[RequestToJoinStageState["WAITING"] = 1] = "WAITING";
    RequestToJoinStageState[RequestToJoinStageState["ACCEPTED"] = 2] = "ACCEPTED";
    RequestToJoinStageState[RequestToJoinStageState["REJECTED"] = 3] = "REJECTED";
    RequestToJoinStageState[RequestToJoinStageState["INITIATED"] = 4] = "INITIATED";
})(RequestToJoinStageState || (RequestToJoinStageState = {}));
export var RequestToJoinType;
(function (RequestToJoinType) {
    RequestToJoinType["present"] = "REQUEST_TO_PRESENT";
    RequestToJoinType["ask"] = "REQUEST_TO_ASK";
})(RequestToJoinType || (RequestToJoinType = {}));
const initialState = {
    id: '',
    peerId: uuid.v4().toString(),
    device: '',
    email: '',
    displayName: '',
    authToken: '',
    loggedIn: false,
    displayImageURL: '',
    audioMuted: false,
    videoOff: false,
    sharingScreen: false,
    videoProduction: MediaStates.NOT_STARTED,
    audioProduction: MediaStates.NOT_STARTED,
    screenSharingProduction: MediaStates.NOT_STARTED,
    shouldProduce: true,
    isHost: false,
    canUnMute: true,
    clientSpecificId: null,
    participantPermissions: {
        camera: permissionEnum.INIT,
        microphone: permissionEnum.INIT,
    },
    cameraFacing: 'front',
    hidden: false,
    webinarHiddenParticipant: false,
    joinStageSettings: JoinStageSettings.ALLOWED,
    requestToJoinStageState: RequestToJoinStageState.NONE,
    presentingState: PresentingState.NOT_PRESENTING,
    canPresent: false,
    metadata: {
        preset_name: 'default',
        view_type: 'GROUP_CALL',
    },
    organizationId: '',
    preset: null,
    switched: null,
};
function idFromAuthToken(token) {
    const decoded = parseJwt(token);
    return decoded.id;
}
async function saveUserName(value) {
    try {
        await AsyncStorage.setItem('dyte-display-name', value);
    }
    catch {
        // pass
    }
}
const participant = createReducer(initialState, {
    [resetParticipant.toString()]: (state) => {
        state.sharingScreen = false;
        state.videoProduction = MediaStates.NOT_STARTED;
        state.audioProduction = MediaStates.NOT_STARTED;
    },
    [setUser.toString()]: (state, action) => {
        state.authToken = action.payload.authToken;
        state.loggedIn = action.payload.loggedIn || false;
        state.email = action.payload.email || '';
        state.displayImageURL = action.payload.picture || '';
        state.id = action.payload.id || '';
        state.clientSpecificId = action.payload.clientSpecificId;
        state.organizationId = action.payload.organizationId;
        if (action.payload.name && action.payload.name.length > 0) {
            state.displayName = action.payload.name || '';
            saveUserName(action.payload.name || '');
        }
    },
    [setUserToken.toString()]: (state, action) => {
        state.authToken = action.payload;
        state.id = idFromAuthToken(action.payload);
    },
    [setUserDisplayName.toString()]: (state, action) => {
        state.displayName = action.payload;
        saveUserName(action.payload);
    },
    [setUserDisplayImageURL.toString()]: (state, action) => {
        state.displayImageURL = action.payload;
    },
    [setLoggedIn.toString()]: (state, action) => {
        state.loggedIn = action.payload;
    },
    [setParticipantPermissions.toString()]: (state, action) => {
        state.participantPermissions = action.payload;
    },
    [setVideoProduction.toString()]: (state, action) => {
        state.videoProduction = action.payload;
    },
    [setAudioProduction.toString()]: (state, action) => {
        state.audioProduction = action.payload;
    },
    [setScreenSharingProduction.toString()]: (state, action) => {
        state.screenSharingProduction = action.payload;
    },
    [setAudioMuted.toString()]: (state, action) => {
        if (state.canUnMute === false) {
            return;
        }
        state.audioMuted = action.payload;
    },
    [setVideoOff.toString()]: (state, action) => {
        state.videoOff = action.payload;
    },
    [setVideoTrackSelection.toString()]: (state, action) => {
        state.videoTrackSelection = action.payload;
    },
    [setAudioTrackSelection.toString()]: (state, action) => {
        state.audioTrackSelection = action.payload;
    },
    [setScreenSharing.toString()]: (state, action) => {
        state.sharingScreen = action.payload;
    },
    [roomJoined.toString()]: (state, action) => {
        state.isHost = action.payload.isHost;
    },
    [muteAll.toString()]: (state, action) => {
        if (!state.isHost) {
            state.audioMuted = true;
            state.canUnMute = action.payload.allowUnMute;
        }
    },
    [muteAllVideo.toString()]: (state) => {
        if (!state.isHost) {
            state.videoOff = true;
        }
    },
    [disableAudio.toString()]: (state) => {
        state.audioMuted = true;
    },
    [disableVideo.toString()]: (state) => {
        state.videoOff = true;
    },
    [setCameraFacing.toString()]: (state, action) => {
        state.cameraFacing = action.payload;
    },
    [requestToJoinStageAccepted.toString()]: (state, action) => {
        state.joinStageSettings = JoinStageSettings.ALLOWED;
        state.requestToJoinStageState = RequestToJoinStageState.ACCEPTED;
        state.presentingState = PresentingState.INITIATED;
        state.requestToJoinType = action.payload.requestToJoinType;
        state.canPresent = true;
    },
    [updateCanPresent.toString()]: (state, action) => {
        state.canPresent = action.payload;
    },
    [updateWebinarPresentingSetting.toString()]: (state, action) => {
        state.webinarHiddenParticipant = action.payload;
    },
    [requestToJoinStageRejected.toString()]: (state) => {
        state.webinarHiddenParticipant = true;
        state.joinStageSettings = JoinStageSettings.NOT_ALLOWED;
        state.requestToJoinStageState = RequestToJoinStageState.REJECTED;
        state.presentingState = PresentingState.NOT_PRESENTING;
        state.sharingScreen = false;
        state.screenSharingProduction = MediaStates.NOT_STARTED;
        Alert.alert('Request Declined', 'Your Request have been declined by host or moderator', [
            { text: 'OK', onPress: () => { } },
        ]);
    },
    [removedFromStage.toString()]: (state, action) => {
        state.webinarHiddenParticipant = true;
        state.joinStageSettings = JoinStageSettings.NOT_ALLOWED;
        state.audioMuted = true;
        state.videoOff = true;
        state.sharingScreen = false;
        state.requestToJoinStageState = RequestToJoinStageState.NONE;
        state.presentingState = PresentingState.NOT_PRESENTING;
        state.screenSharingProduction = MediaStates.NOT_STARTED;
        state.requestToJoinType = undefined;
        const msgTitle = action.payload.type === WebinarAcceptRequestType.REQUESTED_BY_PARTICIPANT ? 'Dropped successfully.' : 'Dropped from Stage';
        const msgTxt = action.payload.type === WebinarAcceptRequestType.REQUESTED_BY_PARTICIPANT
            ? `You are no more ${state.requestToJoinType === RequestToJoinType.present
                ? 'Pesenting' : 'Asking'}.` : `Host/Moderator has force stopped you from ${state.requestToJoinType === RequestToJoinType.present ? 'Pesenting' : 'Asking'}.`;
        Alert.alert(msgTitle, msgTxt, [
            { text: 'OK', onPress: () => { } },
        ]);
        state.canPresent = false;
    },
    [requestedJoinToStageState.toString()]: (state, action) => {
        state.requestToJoinStageState = action.payload;
    },
    [requestToJoinType.toString()]: (state, action) => {
        state.requestToJoinType = action.payload;
    },
    [startedPresenting.toString()]: (state) => {
        state.webinarHiddenParticipant = false;
        state.presentingState = PresentingState.PRESENTING;
    },
    [stoppedPresenting.toString()]: (state) => {
        state.webinarHiddenParticipant = true;
        state.presentingState = PresentingState.NOT_PRESENTING;
        state.screenSharingProduction = MediaStates.NOT_STARTED;
        state.sharingScreen = false;
        state.canPresent = false;
    },
    [initiatePresenting.toString()]: (state) => {
        state.presentingState = PresentingState.INITIATED;
    },
    [requestToJoinPeerStageAccepted.toString()]: (state, action) => {
        if (action.payload.id === state.peerId) {
            state.requestToJoinType = action.payload.requestToJoinType;
        }
    },
    [setVisibilitySettings.toString()]: (state, action) => {
        const { hidden, joinStageSettings } = action.payload;
        state.joinStageSettings = joinStageSettings;
    },
    [updatePreset.toString()]: (state, action) => {
        state.preset = action.payload.preset;
    },
    [peerMetadataUpdated.toString()]: (state, action) => {
        if (state.peerId === action.payload.id) {
            state.metadata.preset_name = action.payload.preset_name;
            state.metadata.view_type = action.payload.view_type;
        }
    },
    [switchToGroupCall.toString()]: (state, action) => {
        state.videoProduction = MediaStates.NOT_STARTED;
        state.audioProduction = MediaStates.NOT_STARTED;
        state.switched = 'meeting';
    },
    [switchToWebinar.toString()]: (state, action) => {
        state.switched = 'webinar';
    },
});
export default participant;
//# sourceMappingURL=participantSlice.js.map