import React, { useEffect, useContext, useState, } from 'react';
import { useWindowDimensions, TextInput, Alert, Platform } from 'react-native';
import { Text, Box, Icon, Button, Flex, mergeStyles, } from '../../themes/components';
import { ConfigServiceContext } from '../../utils/ConfigProvider';
import { GiftedChat, Bubble } from 'react-native-gifted-chat';
import UserAvatar from 'react-native-user-avatar';
import { ThemeContext } from 'styled-components';
import { useSelector, useDispatch } from 'react-redux';
import { MessageTypes, } from '../../types/APITypes';
import { PeersServiceContext } from '../../services/PeersService';
import { MediaRoomContext } from '../../services/MediaRoomService';
import FileViewer from '../../native/FileViewer';
import { launchImageLibrary } from '../../native/ImagePicker';
import DocumentPicker from '../../native/DocumentPicker';
import RNFS from '../../native/FS';
import { useMutation } from 'graphql-hooks';
import { markMessagesRead } from '../../store/roomSlice';
import KeyboardViewSpacer from '../../components/keyboardViewSpace';
import { SDK_BUILD } from '../../env';
import borderRadius from '../../themes/foundations/borderRadius';
// import { ReactNativeFile } from 'apollo-upload-client';
const UPLOAD_FILE = `
    mutation($file: Upload!, $roomName: String!) {
        uploadFile(file: $file, roomName: $roomName) {
            link
        }
    }
`;
const AttachementParentContainerDecider = (props) => (Platform.OS === 'ios'
    ? (<Box {...styles.attachemenetView}>
			{props.children}
		</Box>)
    : (<Flex {...styles.attachemenetView}>
			{props.children}
		</Flex>));
const MobileChatTab = (props) => {
    const dispatch = useDispatch();
    const { meeting, sessionConfig } = useContext(ConfigServiceContext);
    const chatAllowed = sessionConfig.permissions.chat.public.can_send;
    const { colors } = useContext(ThemeContext);
    const windowDimensions = useWindowDimensions();
    const chatMessages = useSelector((state) => state.room.chatMessages);
    const { selfPeer } = useContext(PeersServiceContext);
    const { height, width } = sessionConfig.theme.dimensions || windowDimensions;
    const [text, onChangeText] = React.useState('');
    const [showAttachments, toggleAttachments] = React.useState(false);
    const { mediaRoom } = useContext(MediaRoomContext);
    const [loadingPicker, setLoadingPicker] = React.useState(false);
    const [messages, setMessages] = useState([]);
    const roomName = useSelector((state) => state.room.roomName);
    const polls = useSelector((state) => state.room.polls);
    const userVotedFor = React.useState({});
    const unread = chatMessages.filter((m) => m.read !== true && m.type !== MessageTypes.poll);
    // const drawerHeight = Math.floor(height*2/3);
    const [uploadFile] = useMutation(UPLOAD_FILE);
    useEffect(() => {
        const msgs = [...chatMessages].filter((m) => m.type !== MessageTypes.poll);
        if (messages.length !== msgs.length) {
            setMessages(msgs.reverse().map((m) => {
                const messageBase = {
                    type: m.type,
                    _id: Math.round(Math.random() * 1000000),
                    user: {
                        _id: m.userId,
                        name: m.displayName,
                    },
                };
                if (m.type === MessageTypes.text) {
                    return {
                        ...messageBase,
                        text: m.message,
                    };
                }
                if (m.type === MessageTypes.image) {
                    return {
                        ...messageBase,
                        image: m.link,
                    };
                }
                if (m.type === MessageTypes.file) {
                    return {
                        ...messageBase,
                        text: m.name,
                        link: m.link,
                    };
                }
                // 	const { pollId } = m;
                // 	const pollData = polls[pollId];
                // 	const { options, question } = pollData;
                // 	const selfId = selfPeer.userId;
                // 	return {
                // 		...messageBase,
                // 		text: question,
                // 		polls: {
                // 			pollId,
                // 			options: options.map((el) => {
                // 				const selfVote = el.votes.find((v) => v.id === selfId);
                // 				if (selfVote) {
                // 					return {
                // 						...el,
                // 						selected: true,
                // 					};
                // 				}
                // 				return {
                // 					...el,
                // 					selected: false,
                // 				};
                // 			}),
                // 			onOptionSelected: onVotedInAPoll,
                // 		},
                // 	};
                // }
                return {};
            }));
        }
    }, [chatMessages, polls]);
    useEffect(() => {
        // if (unread.length > 0) dispatch(markMessagesRead(null));
        if (unread.length > 0) {
            dispatch(markMessagesRead({
                [MessageTypes.text]: true,
                [MessageTypes.file]: true,
                [MessageTypes.image]: true,
            }));
        }
    }, [unread]);
    function onVotedInAPoll(pollId, selectetAnswer, index) {
        mediaRoom.votePoll({
            index,
            pollId,
        });
    }
    const onTextMessageSend = () => {
        if (text !== '') {
            const t = {
                message: text,
                userId: selfPeer.userId,
                displayName: selfPeer.displayName,
                type: MessageTypes.text,
            };
            mediaRoom.sendMessage(t);
            onChangeText('');
        }
    };
    const sendImage = (link) => {
        const image = {
            displayName: selfPeer.displayName,
            type: MessageTypes.image,
            link,
            userId: selfPeer.id,
        };
        mediaRoom.sendMessage(image);
    };
    const sendFile = (link, name, size) => {
        const file = {
            displayName: selfPeer.displayName,
            type: MessageTypes.file,
            link,
            userId: selfPeer.id,
            name,
            size,
        };
        mediaRoom.sendMessage(file);
    };
    async function uploadItems(file) {
        try {
            // const file = new ReactNativeFile(fileData)
            const { link } = (await uploadFile({ variables: { file, roomName } })).data.uploadFile;
            return link;
        }
        catch (error) {
            console.log(error);
            // throw Error()
        }
    }
    const onSelectImage = () => {
        try {
            if (!loadingPicker) {
                setLoadingPicker(true);
                toggleAttachments(false);
                launchImageLibrary({ mediaType: 'photo' }, async (res) => {
                    setLoadingPicker(false);
                    // TODO: Error Handling here
                    // For example user have not give permission to share images
                    const { uri, didCancel, errorCode, errorMessage, fileName, type, fileSize, } = res;
                    if (didCancel) {
                        // console.log('User cancelled image picker');
                    }
                    else if (errorCode) {
                        return Alert.alert('Error', `Error: ${errorMessage}`, [
                            { text: 'OK' },
                        ]);
                    }
                    else {
                        const imgProps = {
                            name: fileName,
                            type,
                            uri,
                        };
                        const link = await uploadItems(imgProps);
                        sendImage(link);
                    }
                });
            }
        }
        catch (error) {
            console.log(error);
            setLoadingPicker(false);
            return Alert.alert('Error', 'Error: Problem uploading image', [
                { text: 'OK' },
            ]);
        }
    };
    const onSelectAttachement = async () => {
        if (!loadingPicker) {
            setLoadingPicker(true);
            toggleAttachments(false);
            try {
                const res = await DocumentPicker.pick({
                    type: [DocumentPicker.types.allFiles],
                });
                const { uri, name, size } = res;
                const file = {
                    displayName: selfPeer.displayName,
                    type: MessageTypes.file,
                    link: uri,
                    userId: selfPeer.id,
                    name,
                    size,
                };
                const link = await uploadItems(file);
                sendFile(link, name, size);
                setLoadingPicker(false);
            }
            catch (err) {
                setLoadingPicker(false);
                if (DocumentPicker.isCancel(err)) {
                    // User cancelled the picker, exit any dialogs or menus and move on
                }
                else {
                    throw err;
                }
            }
        }
    };
    const viewAttachedFile = async (path, fileName) => {
        try {
            const localFile = `${RNFS.DocumentDirectoryPath}/${fileName}`;
            const options = {
                fromUrl: path,
                toFile: localFile,
            };
            await RNFS.downloadFile(options).promise;
            await FileViewer.open(localFile);
        }
        catch {
            return Alert.alert('Error', 'Unable to open attached file', [
                { text: 'OK' },
            ]);
        }
    };
    const renderAttachments = () => (showAttachments && (<AttachementParentContainerDecider>
				<Button onClick={onSelectImage}>
					<Box {...styles.attachementButtons}>
						<Icon name="image" fill="textPrimary.100"/>
						<Text ml={8}> Images</Text>
					</Box>
				</Button>
				<Button onClick={onSelectAttachement}>
					<Box {...mergeStyles(styles.attachementButtons, {
        width: Platform.OS === 'ios' ? 150 : 120,
    })}>
						<Icon name="attach-file" fill="textPrimary.100"/>
						<Text ml={Platform.OS === 'ios' ? 8 : 0}> Attachments</Text>
					</Box>
				</Button>
			</AttachementParentContainerDecider>));
    const renderBubble = (props) => {
        const { type, link, text } = props.currentMessage;
        return (<Bubble {...props} onLongPress={type === MessageTypes.file
            ? () => viewAttachedFile(link, text)
            : undefined} wrapperStyle={{
            left: {
                backgroundColor: colors.secondary[800],
                borderRadius: borderRadius.medium,
                paddingVertical: 6,
                paddingHorizontal: 3,
            },
            right: {
                backgroundColor: colors.secondary[800],
                borderRadius: borderRadius.medium,
                paddingVertical: 6,
                paddingHorizontal: 3,
            },
        }} textStyle={{
            left: {
                color: colors.textPrimary[100],
            },
            right: {
                color: colors.textPrimary[100],
            },
        }}/>);
    };
    return (<Flex height={height - 30} align="center">
			<KeyboardViewSpacer>
			<GiftedChat messages={messages} alwaysShowSend renderAvatarOnTop renderUsernameOnMessage isKeyboardInternallyHandled={Platform.OS === 'android' ? false : true} renderAvatar={(props) => (<UserAvatar name={props.currentMessage.user.name} bgColor={colors.primary[700]}/>)} renderFooter={() => <Box height={10}/>} renderBubble={renderBubble} renderInputToolbar={(props) => {
        if (chatAllowed) {
            return (<Flex width={width - 20} direction="row" justify="space-between" align="center" bg="secondary.800" borderRadius="50px">

						<Box position="relative">
							{!SDK_BUILD && <Button onClick={() => {
                toggleAttachments(!showAttachments);
            }}>
								<Box {...mergeStyles(styles.touchableIcons, {
                ml: 8,
            })}>
									{!showAttachments ? (<Icon name="plus-thick" fill="textPrimary.100" boxSize="sm"/>) : (<Icon name="close" fill="textPrimary.100" boxSize="sm"/>)}
								</Box>
							</Button>}
							{renderAttachments()}
						</Box>
						<TextInput style={{
                color: colors.textPrimary[300],
                paddingHorizontal: 5,
                height: 40,
                width: width - 120,
            }} onChangeText={onChangeText} value={text}/>

						<Button onClick={onTextMessageSend}>
							<Box {...mergeStyles(styles.touchableIcons, {
                backgroundColor: 'primary.500',
                mr: 8,
            })}>
								<Icon name="send" fill="textPrimary.100" boxSize="md"/>
							</Box>
						</Button>

					</Flex>);
        }
        else
            return null;
    }} user={{
        _id: selfPeer.userId,
        name: selfPeer.displayName,
    }}/>
			</KeyboardViewSpacer>
		</Flex>);
};
const styles = {
    attachementButtons: {
        display: 'flex',
        flexDirection: 'row',
        backgroundColor: 'secondary.700',
        marginTop: 20,
        marginRight: 5,
        width: 100,
        height: 35,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 30,
    },
    touchableIcons: {
        backgroundColor: 'secondary.700',
        borderRadius: 15,
        width: 30,
        height: 30,
        align: 'center',
        justify: 'center',
        mt: 8,
        mb: 8,
    },
    attachemenetView: {
        position: 'absolute',
        top: Platform.OS === 'ios' ? -130 : -15,
        left: Platform.OS === 'ios' ? 8 : 48,
        direction: Platform.OS === 'ios' ? 'column' : 'row',
    },
};
export default MobileChatTab;
//# sourceMappingURL=MobileChatTab.js.map