import React, { Component } from 'react'
import { withStyles, getMuiTheme } from '@material-ui/core/styles';
import Layout from '../components/MyLayout.js'
import Paper from '@material-ui/core/Paper';
import axios from 'axios'
import FormLabel from '@material-ui/core/FormLabel';
import FormControl from '@material-ui/core/FormControl';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
import Snackbar from '@material-ui/core/Snackbar';
import SnackbarContent from '@material-ui/core/SnackbarContent';
import { cloneDeep } from 'lodash';
import getConfig from 'next/config'
import Typography from '@material-ui/core/Typography';


var EdeclicLib=null

const { publicRuntimeConfig } = getConfig()
//variable for client side only import
let back = ''


const styles = theme => ({
    root: {
        margin: theme.spacing.unit,

    },
    paper: {
        width: 400,
        [theme.breakpoints.down('md')]: {
            width: `${100 - (theme.spacing.unit)}vw`
        },
        padding: theme.spacing.unit * 2
    },
    colorSwitchBase: {
        color: theme.palette.primary,
        '&$colorChecked': {
            color: theme.palette.primary,
            '& + $colorBar': {
                backgroundColor: theme.palette.primary,
            },
        },
    },
    colorBar: {},
    colorChecked: {},
    bandeau: {
        maxHeight: '5vh',
        width: '100%',
        backgroundColor: theme.palette.secondary,
        margin: theme.spacing.unit * 2

    }

})

class parametres extends Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);

    }
    state = {
        general: false,
        topics: publicRuntimeConfig.push.topics,
        loading: false,
        openSnack: false,
        error: false,
        warning: false,
        success: false,
        snackMessage: "",
        isSafari: false
    };

    async componentDidMount() {

        EdeclicLib = (await import('../components/firebase-client.js')).default
        if (!EdeclicLib.messaging)
            return
        if (EdeclicLib.isSupported() === false) {
            this.setState({ isSafari: true });
            return;
        }
      
        EdeclicLib.askForToken().then((token) => {
            console.log("componentDidMount token received :");
            console.log(token);
            const url = "/push/info/" + token
            axios.get(url).then(response => {
                this.refreshCheckboxes(!!token, response.data.topics)
            }).catch(error => {
                console.log(error)
                if (error.status != 500) {
                    if (process.browser) {


                    }
                }
            })
        }).catch(error => {
            console.log("error out" + error)
            if (error.status != 500) {
                if (process.browser) {

                }
            }
        });


    }

    refreshCheckboxes(hasToken, topics) {
        //general
        this.setState({ general: hasToken })

        //all topics
        if (!!topics) {
            const topicsTemp = cloneDeep(this.state.topics)
            topicsTemp.map(temp =>
                temp.value = !!topics[temp.key]
            )
            this.setState({ topics: topicsTemp })
        }

    }

    async sendPushTopicSubscription(topic) {
        var token = await EdeclicLib.askForToken();

        const url = "/push/subscribe"
        axios.post(url, {
            token, topic
        }).then(response => {
            this.setState({ success: true, error: false, warning: false, message: '', snackMessage: "Le topic a bien  été ajouté.", loading: false, openSnack: true })
        }).catch(error => {
            if (error.status != 500) {
                if (process.browser) {
                    // client-side-only code
                    // back.saveEventDataLocally([{ message: this.state.message }]);
                }
            }
            this.setState({ success: false, error: false, warning: true, snackMessage: "📴 Votre souscription au topic n'a pas pu aboutir, mais a été sauvegardé. Nous l'enverrons lorsque nous aurons une meilleure connectivité.", loading: false, openSnack: true })
        });
    }
    async sendPushTopicUnSubscription(topic) {
        var token = await EdeclicLib.askForToken();

        const url = "/push/unsubscribe"
        axios.post(url, {
            token, topic
        }).then(response => {
            this.setState({ success: true, error: false, warning: false, message: '', snackMessage: "Le topic a bien été retiré.", loading: false, openSnack: true })
        }).catch(error => {
            if (error.status != 500) {
                if (process.browser) {
                    // client-side-only code
                    //back.saveEventDataLocally([{ message: this.state.message }]);
                }
            }
            this.setState({ success: false, error: false, warning: true, snackMessage: "📴 Votre désengagement au topic n'a pas pu aboutir, mais a été notifié. Nous l'enverrons lorsque nous aurons une meilleure connectivité.", loading: false, openSnack: true })
        });
    }
    handleChange = name => event => {

        if (name === 'general') {
            console.log('general')
            if (event.target.checked === true) {
                console.log('event.target.checked === true')
                
                if (!process.browser) return
                EdeclicLib.askForToken();
                console.log('token asked')
                this.setState({ general: true })
            }
            else {
                console.log('')
                
                if (!process.browser) return
                EdeclicLib.deleteToken();
                let topicsTemp = cloneDeep(this.state.topics)
                topicsTemp.map(a => a.value = false)
                this.setState({ topics: topicsTemp, general: false })
                console.log('')
            }
        }
        else {
            if (event.target.checked === true) {
                this.sendPushTopicSubscription(name)
            }
            else {
                this.sendPushTopicUnSubscription(name)
            }

            let topicsTemp = cloneDeep(this.state.topics)
            topicsTemp.map(temp => {
                if (temp.key === name)
                    temp.value = event.target.checked
            })

            this.setState({ topics: topicsTemp, general: true })
        }


    };

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

    render() {

        const { classes } = this.props;

        return (
            <Layout   menu={this.props.menu}>
                <div className={classes.root}>
                    <div className={classes.bandeau} hidden={!this.state.isSafari}>
                        <Typography variant="h6">🚧 Votre navigateur ne permet pas la reception de notification. 🚧</Typography>
                    </div>
                    <Paper elevation={4} className={classes.paper}>
                        <FormControl component="fieldset">
                            <FormLabel component="legend">Je souhaites recevoir des notifications : </FormLabel>
                            <FormGroup>
                                <FormControlLabel
                                    control={
                                        <Switch
                                            disabled={this.state.isSafari}
                                            checked={this.state.general}
                                            onChange={this.handleChange('general')}
                                            value="general"
                                            classes={{
                                                switchBase: classes.colorSwitchBase,
                                            }}
                                        />
                                    }
                                    label="Générales"
                                />

                                {this.state.topics.map(ar =>

                                    <FormControlLabel key={ar.key}
                                        control={
                                            <Switch
                                                disabled={this.state.isSafari}
                                                checked={ar.value}
                                                onChange={this.handleChange(ar.key)}
                                                value={ar.key}
                                            />
                                        }
                                        label={`Sur ${ar.key}`}
                                    />, this)}
                            </FormGroup>
                        </FormControl>
                    </Paper>
                </div>

                <Snackbar
                    autoHideDuration={4000}
                    anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
                    open={this.state.openSnack}
                    onClose={this.handleClose}
                    ContentProps={{
                        'aria-describedby': 'message-id',
                    }}
                >
                    <SnackbarContent

                        aria-describedby="message-id"
                        className={classes[this.state.error ? 'error' : this.state.warning ? 'warning' : 'success']}
                        message={<span id="message-id">{this.state.snackMessage}</span>}
                    /></Snackbar>
            </Layout >
        )
    }
}

export default withStyles(styles)(parametres)