import React, { useContext } from 'react';
import { ThemeContext } from 'styled-components';
import UserAvatar from 'react-native-user-avatar';
import { ScrollView, TouchableWithoutFeedback } from 'react-native';
import OptionsMenu from '../../components/ui-menu';
import { RequestToJoinType, } from '../../store/participantSlice';
import { useSelector } from 'react-redux';
import { WebinarAcceptRequestType, DyteViewTypes } from '../../types/newTypes';
import borderRadius from '../../themes/foundations/borderRadius';
import { PeersServiceContext } from '../../services/PeersService';
import { Text, Box, Icon, Flex, Button, HStack, } from '../../themes/components';
import PeerName from '../../components/PeerName';
import { MediaRoomContext } from '../../services/MediaRoomService';
import { ConfigServiceContext } from '../../utils/ConfigProvider';
const ParticipantListVariants = {
    hidden: {
        y: -20,
        opacity: 0,
        scale: 0.96,
    },
    visible: {
        opacity: 1,
        y: 0,
    },
    hovered: {
        scale: 1,
    },
    exit: {
        opacity: 0,
        scale: 0,
    },
};
function AcceptDeclinePeers({ rejectRequest, acceptRequest, peer, type, }) {
    const { colors } = useContext(ThemeContext);
    return (<Flex direction="row" align="center" justify="space-between" bg="secondary.800" p={8} mt={8} borderRadius={borderRadius.medium}>
			<Flex direction="row" align="center">
				<UserAvatar name={`${peer.name}`} bgColor={colors.primary[500]}/>
				<Text ml={10} color={colors.textPrimary[200]} textAlign="center" fontWeight="bold">
					<PeerName name={peer.name > 30 ? `${peer.name.substring(0, 20)}...` : `${peer.name}`} charSize={30}/>
					{peer.isMe ? ' (me)' : null}
				</Text>
			</Flex>
			<Flex ml="auto" mr={2} direction="row">
				<Box mr={6}>
					<Button onClick={() => acceptRequest(peer.id, type)}>
						<Icon boxSize="xl" name="check" fill={colors.success[500]}/>
					</Button>
				</Box>
				<Box ml={6}>
					<Button onClick={() => rejectRequest(peer.id)}>
						<Icon boxSize="xl" name="clear" fill={colors.danger[500]}/>
					</Button>
				</Box>
			</Flex>
		</Flex>);
}
function Participant({ peer, mediaRoom, permissions, roomViewType, }) {
    const { colors } = useContext(ThemeContext);
    const { participantControls } = useContext(ConfigServiceContext);
    // TODO: Probably missing permissions
    const anyPermissions = permissions?.pin_participant
        || permissions?.can_allow_participant_audio
        || permissions?.can_allow_participant_video
        || permissions?.kick_participant;
    const showWebinarHostControls = permissions.accept_present_requests;
    const options = [];
    // h
    if (anyPermissions || participantControls.length > 0) {
        if (permissions?.pin_participant) {
            if (peer.isPinned) {
                options.push({
                    title: 'Unpin',
                    onClick: () => mediaRoom.pin(null),
                });
            }
            else {
                options.push({
                    title: 'Pin',
                    onClick: () => mediaRoom.pin(peer.id),
                });
            }
        }
        if (permissions?.can_allow_participant_audio) {
            options.push({
                title: 'Mute Audio',
                onClick: () => mediaRoom.disableAudio(peer.id),
            });
        }
        if (permissions?.can_allow_participant_video) {
            options.push({
                title: 'Disable Video',
                onClick: () => mediaRoom.disableVideo(peer.id),
            });
        }
        if (permissions?.kick_participant && !peer.isMe) {
            options.push({
                title: 'Kick',
                onClick: () => mediaRoom.kick(peer.id),
            });
        }
        if (roomViewType === DyteViewTypes.webinar
            && !peer.isMe && showWebinarHostControls && !peer.webinarHiddenParticipant) {
            options.push({
                title: 'Force Stop Presenting',
                onClick: () => mediaRoom.removePeerFromStage(peer.id, WebinarAcceptRequestType.REQUESTED_BY_MODERATOR),
            });
        }
        if (roomViewType === DyteViewTypes.webinar
            && !peer.isMe && showWebinarHostControls) {
            options.push({
                title: 'Grant Premission to Present',
                onClick: () => mediaRoom.acceptAllRequestToJoinStage([{
                        id: peer.id,
                        requestToJoinType: RequestToJoinType.present,
                        type: WebinarAcceptRequestType.REQUESTED_BY_MODERATOR,
                    }]),
            });
        }
        /* if (roomViewType === DyteViewTypes.webinar && !peer.isMe && showWebinarHostControls) {
            options.push({
                title: 'Grant Premission to Ask',
                onClick: () => mediaRoom.acceptAllRequestToJoinStage(
                    [{
                        id: peer.id,
                        requestToJoinType: RequestToJoinType.ask,
                        type: WebinarAcceptRequestType.REQUESTED_BY_MODERATOR,
                    }],
                ),
            });
        } */
        participantControls.forEach((p) => {
            if (!peer.isMe || p.showSelf !== false) {
                options.push({
                    title: p.label,
                    onClick: () => p.onClick(peer.id),
                });
            }
        });
        options.push({
            title: 'Cancel',
            onClick: () => { },
        });
    }
    return (<Flex direction="row" align="center" justify="space-between" bg="secondary.800" p={8} mt={8} borderRadius={borderRadius.medium}>
			<Flex direction="row" align="center">
				<UserAvatar name={`${peer.displayName}`} bgColor={colors.primary[500]}/>
				<HStack ml={10} color={colors.textPrimary[200]} textAlign="center" fontWeight="bold">
					<PeerName name={peer.displayName.length > 30 ? `${peer.displayName.substring(0, 20)}...` : `${peer.displayName}`} charSize={30}/>
					{(peer.isMe || peer.label) && (<Text background="primary.300" color="textPrimary.100" pr={4} ml={4} borderRadius={3}>

							{peer.isMe ? 'me' : peer.label}
						</Text>)}
				</HStack>
			</Flex>
			<Flex ml="auto" mr={2} direction="row">
				<Box mr={8}>
					{peer.producingAudio ? <Icon boxSize="xl" name="mic" fill={colors.textPrimary[400]}/> : <Icon boxSize="xl" name="mic-off" fill={colors.danger[500]}/>}
				</Box>
				{peer.producingVideo ? <Icon boxSize="xl" name="videocam" fill={colors.textPrimary[400]}/>
        : <Icon boxSize="xl" name="videocam-off" fill={colors.danger[500]}/>}
				{(anyPermissions || participantControls.length > 0) && (<OptionsMenu options={options.map((option) => option.title)} actions={options.map((option) => option.onClick)}/>)}
			</Flex>
		</Flex>);
}
export default function ParticipantsTab() {
    const roomViewType = useSelector((state) => state.room.roomViewType);
    const peersService = useContext(PeersServiceContext);
    let { processedPeers } = peersService;
    const { selfPeer, joinedProcessedPeers } = peersService;
    const { mediaRoom } = useContext(MediaRoomContext);
    const { sessionConfig } = useContext(ConfigServiceContext);
    const requestToJoinPeersList = useSelector((state) => state
        .room.requestToJoinPeersList);
    const requestToPresentPeers = requestToJoinPeersList.filter((el) => el.requestToJoinType === RequestToJoinType.present);
    const requestToAskPeers = requestToJoinPeersList.filter((el) => el.requestToJoinType === RequestToJoinType.ask);
    processedPeers = [selfPeer].concat(processedPeers.sort((a, b) => a.id.localeCompare(b.id))).filter((el) => !el?.webinarHiddenParticipant);
    const attendeesList = [selfPeer].concat(joinedProcessedPeers).filter((el) => el?.webinarHiddenParticipant).filter((v, i, a) => a.findIndex((t) => (t.id === v.id)) === i);
    const askPeerList = [selfPeer].concat(joinedProcessedPeers).filter((el) => !el?.webinarHiddenParticipant && el.requestToJoinType === RequestToJoinType.ask);
    processedPeers = processedPeers.concat(askPeerList)
        .filter(((set) => (o) => (set.has(o.id) ? false : set.add(o.id)))(new Set()));
    const acceptRequest = (peerId, requestToJoinType) => {
        mediaRoom.acceptAllRequestToJoinStage([{
                id: peerId,
                requestToJoinType,
                type: WebinarAcceptRequestType.REQUESTED_BY_PARTICIPANT,
            }]);
    };
    const rejectRequest = (peerId) => {
        mediaRoom.rejectRequestToJoinStage(peerId);
    };
    const handleAcceptAll = (peersList) => {
        mediaRoom.acceptAllRequestToJoinStage(peersList.map((el) => ({ id: el.id, requestToJoinType: el.requestToJoinType })));
    };
    // const testConfig = {
    // 	pinParticipant: true,
    // 	disableParticipantAudio: true,
    // 	disableParticipantVideo: true
    // }
    return (<Flex mt={60}>
			<ScrollView style={{ padding: 20 }}>
				<TouchableWithoutFeedback>
					<Box>
						<Box my={20}>
							{roomViewType === DyteViewTypes.webinar && processedPeers.length > 0
        && (<Text fontSize={16} fontWeight="bold" mb={10}>
							Presenting (
							{processedPeers.length}
							)
						</Text>)}
							{processedPeers.map((p) => (<Participant peer={p} key={p.id} mediaRoom={mediaRoom} permissions={sessionConfig?.permissions} roomViewType={roomViewType}/>))}
						</Box>

						{attendeesList.length > 0
        && (<Box>
						<Text fontSize={16} fontWeight="bold" mt={20} mb={10}>
							{' '}
							Attending (
							{attendeesList.length}
							)
						</Text>
						{attendeesList.map((p) => (<Participant key={p.id} peer={p} mediaRoom={mediaRoom} permissions={sessionConfig?.permissions} roomViewType={roomViewType}/>))}
					</Box>)}
						{requestToAskPeers.length > 0
        && (<Box>
						<Text fontSize={16} fontWeight="bold" mt={20} mb={10}>
							{' '}
							Want to ask Question (
							{requestToAskPeers.length}
							)
						</Text>
						{requestToAskPeers.map((p) => (<AcceptDeclinePeers rejectRequest={rejectRequest} acceptRequest={acceptRequest} peer={p} key={p.id} type="REQUEST_TO_ASK"/>))}
					</Box>)}
						{requestToPresentPeers.length > 0
        && (<Box>
						<Text fontSize={16} fontWeight="bold" mt={20} mb={10}>
							{' '}
							Want to Present (
							{requestToPresentPeers.length}
							)
						</Text>
						{requestToPresentPeers.map((p) => (<AcceptDeclinePeers rejectRequest={rejectRequest} acceptRequest={acceptRequest} peer={p} key={p.id} type="REQUEST_TO_PRESENT"/>))}
					</Box>)}
						<Box height={200}>
							
						</Box>
					</Box>
				</TouchableWithoutFeedback>
			</ScrollView>

		</Flex>);
}
//# sourceMappingURL=ParticipantsTab.js.map