import React from 'react';
import {MdTranslate} from 'react-icons/md';
import {withNamespaces} from 'react-i18next';
import {withTheme} from "../lib/theme";
import {i18nEvents} from "../lib/i18n";

const styling = theme => ({
    wrapper: {
        position: 'relative',
    },
    selection: {
        position: 'absolute',
        zIndex: 100,
        background: theme.accent.blue,
        transform: 'translateX(-50%)',
        left: '50%',
        top: 'calc(100% - ' + theme.gutter.base * 2 + 'px)'
    },
    toggle: {
        /*display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',*/
        height: '100%',
        margin: '0 -6px',
        padding: '0 6px'
    },
    btn: {
        display: 'block',
        // todo: add theme color
        color: '#000000',
        //color: theme.textColor,
        padding: theme.gutter.base * 2 + 'px ' + theme.gutter.base * 4 + 'px',
        margin: '0 0 2px 0'
    }
});

class LocaleSwitch extends React.Component {
    state = {
        open: false
    };

    render() {
        const {match, history, theme, i18n} = this.props;

        /**
         * Change the current language, get the current url and url scheme, search for key `:lng` in pathscheme and use that index to manipulate history
         * @param lng
         */
        const changeLanguage = (lng) => {
            let cur_path = history.location.pathname.substr(1).split('/');
            let path_pos = match.path.substr(1).split('/').indexOf(':lng');

            i18nEvents.trigger('languageChanging', [lng, history]);

            cur_path[path_pos] = lng;
            i18n.changeLanguage(lng);
            history.push('/' + cur_path.join('/'));
        };

        /**
         * Open/Close Language Switch
         */
        const toggle = () => {
            this.setState({open: !this.state.open})
        };

        const styles = styling(theme);
        return (
            <div className={this.props.className} style={styles.wrapper}>
                <button onClick={toggle} style={styles.toggle}><MdTranslate color={theme.textColor} size={'1.5em'}/></button>

                {this.state.open ? <div style={styles.selection}>
                    <button style={styles.btn} onClick={() => {
                        toggle();
                        changeLanguage('de')
                    }}>de
                    </button>
                    <button style={styles.btn} onClick={() => {
                        toggle();
                        changeLanguage('en')
                    }}>en
                    </button>
                </div> : null}
            </div>
        )
    }
}

export default withNamespaces()(withTheme(LocaleSwitch));