import React, { Component, Fragment } from 'react'
import { Snackbar } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles'
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';

import Link from 'next/link'

const styles = theme => ({
    close: {
        padding: theme.spacing.unit / 2,
    },
});
var EdeclicLib = null
class Messager extends Component {
    state = {
        openSnack: false,
        title: '',
        body: '',
        link: '',
        tokenStopListener: null,
        messageStopListener: null,
    }
    constructor(props) {
        super(props);
    }

    async componentDidMount() {
        EdeclicLib = (await import('./firebase-client.js')).default
        if (!EdeclicLib.messaging)
            return
        this.setState({ tokenStopListener: EdeclicLib.messaging.onTokenRefresh(this.RefreshToken) })
        this.setState({ messageStopListener: EdeclicLib.messaging.onMessage(this.MessageReceiver) })
        
    }
    componentWillUnmount() {
        
        if (process.browser) {
        if (!EdeclicLib.messaging)
            return
        if (!!this.state.tokenStopListener)
            this.state.tokenStopListener();
        if (!!this.state.messageStopListener)
            this.state.messageStopListener();
        }
    }

    RefreshToken = () => {
        EdeclicLib.messaging.getToken().then(function (refreshedToken) {
            console.info('Token refreshed.');
            // Indicate that the new Instance ID token has not yet been sent to the
            // app server.
            EdeclicLib.setTokenSentToServer(false);
            // Send Instance ID token to app server.
            EdeclicLib.sendTokenToServer(refreshedToken);

        }).catch(function (err) {
            console.warning('Unable to retrieve refreshed token ', err);

        });
    }
    // Handle incoming messages. Called when:
    // - a message is received while the app has focus
    // - the user clicks on an app notification created by a service worker
    //   `messaging.setBackgroundMessageHandler` handler.
    MessageReceiver = (payload) => {
        console.info('Message received in Messager. ', payload);

        this.setState({
            openSnack: true,
            title: payload.notification.title,
            body: payload.notification.body,
            link: payload.notification.click_action
        });

    }
    handleClose = () => {
        this.setState({ openSnack: false });

    }
    render() {
        const { classes } = this.props;
        return (
            <Fragment>

                <Snackbar
                    anchorOrigin={{
                        vertical: 'top',
                        horizontal: 'right',
                    }}
                    open={this.state.openSnack}
                    autoHideDuration={6000}
                    onClose={this.handleClose}
                    ContentProps={{
                        'aria-describedby': 'message-id',
                    }}
                    message={<span id="message-id">{this.state.title + " : " + this.state.body}</span>}
                    action={[
                        <Link href={this.state.link}><a>Voir</a></Link>,
                        <IconButton
                            key="close"
                            aria-label="Close"
                            color="inherit"
                            className={classes.close}
                            onClick={this.handleClose}
                        >
                            <CloseIcon />
                        </IconButton>,
                    ]}
                />
            </Fragment>
        )
    }
}
export default withStyles(styles)(Messager);
