import React from 'react';
import {MdDeleteSweep, MdCheck} from 'react-icons/md';
import {withNamespaces} from 'react-i18next';

import {injectSheet, withTheme} from '../../lib/theme';
import {withPusher} from "../../component/PushToApi/Pusher";

const theming = (theme) => ({
    wrapper: {
        display: 'table',
    },
    row: {
        display: 'table-row',
    },
    item: {
        display: 'table-cell',
        verticalAlign: 'middle',
        lineHeight: '1.45rem',
        padding: '0 ' + theme.gutter.base * 2 + 'px',
        '&:first-child': {
            paddingLeft: 0
        },
        '&:last-child': {
            paddingRight: 0
        }
    },
    icon: {
        verticalAlign: 'middle'
    }
});

class Overview extends React.Component {
    evts = [];

    state = {
        clientCacheCleared: false
    };

    componentWillUnmount() {
        this.evts.forEach((id) => {
            clearTimeout(id);
        });
    }

    clearClientCache = () => {
        let tmp_jwt = window.localStorage.getItem('jwt');
        window.localStorage.clear();
        window.localStorage.setItem('jwt', tmp_jwt);
        this.setState({
            clientCacheCleared: true
        });

        let id = setTimeout(() => {
            this.setState({
                clientCacheCleared: false
            })
        }, 800);
        this.evts.push(id);

        window.location.reload(true);
    };

    render() {
        const {t, theme, classes} = this.props;

        return (
            <div>
                <h1>{t('title')}</h1>
                <div className={classes.wrapper}>
                    <div className={classes.row}>
                        <p className={classes.item}>
                            {t('clear-client-cache.lbl')}
                        </p>
                        <button className={classes.item} onClick={this.clearClientCache}>
                            <MdDeleteSweep size={'1.25em'} color={theme.textColor} className={classes.icon}/>
                        </button>
                        {this.state.clientCacheCleared ? <p className={classes.item}><MdCheck size={'1.25em'} color={theme.textColor} className={classes.icon}/></p> : null}
                    </div>
                </div>
            </div>
        );
    }
}

export default withNamespaces('page--settings')(withPusher(withTheme(injectSheet(theming)(Overview))));