import React from 'react';
import {MdDone} from 'react-icons/md';
import {withNamespaces} from 'react-i18next';
import {MdSubdirectoryArrowRight, MdCreateNewFolder, MdAutorenew, MdViewHeadline, MdViewModule} from 'react-icons/md';
import posed from 'react-pose';

import Loading from "../../component/Loading";
import {ButtonSmall, InputText} from '../Form';
import {injectSheet, withTheme} from '../../lib/theme';
import StyleGrid from "../../lib/StyleGrid";
import {ApiRequest, POST} from '../../lib/ApiRequest';
import {withPusher} from "../PushToApi/Pusher";

const theming = (theme) => ({
    wrapper: {
        display: 'flex',
        padding: theme.gutter.base + 'px',
        flexWrap: 'wrap',
        [StyleGrid.smUp]: {}
    },
    wrapperAddDir: {
        display: 'flex',
        overflow: 'hidden',
        [StyleGrid.smUp]: {}
    },
    btn: {
        padding: '0 ' + theme.gutter.base + 'px'
    }
});

const Wrapper = posed.div({
    hidden: {
        height: 0,
    },
    visible: {
        height: 'auto',
    }
});

class ControlBar extends React.Component {
    state = {
        openAddDir: false,
        saving: false,
        newDir: ''
    };

    handleChange = (event) => {
        this.setState({newDir: event.target.value});
    };

    enterCreateDir = (e) => {
        e.preventDefault();
        if(e.keyCode === 27) {
            this.setState({openAddDir: false});
        }

        if(e.keyCode === 13) {
            this.createDir();
        }
    };

    createDir = () => {
        this.props.addPushing(
            {
                name: 'createDir',
                context: 'createDir',
                push: (resolve, reject) => {
                    this.setState({saving: 'progress'});

                    (new ApiRequest('api', POST, 'files/create-dir/' + (this.props.currentDir ? encodeURIComponent(this.props.currentDir + '/' + this.state.newDir) : encodeURIComponent('/' + this.state.newDir))))
                        .debug(true)
                        .header({})
                        .exec()
                        .then((res) => {
                            if(res && res.data) {
                                resolve(res.data);
                            } else {
                                reject();
                            }
                        })
                        .catch(() => {
                            reject();
                        });
                }
            })
            .then((data) => {
                if(data.error) {
                    this.setState({saving: 'error'});
                    return;
                }

                this.setState({
                    saving: 'success',
                    newDir: ''
                });
                this.props.loadList(this.props.currentDir);

                setTimeout(() => {
                    this.setState({saving: false});
                }, 4000);
            })
            .catch((data) => {
                if(!data.cancelled) {
                    this.setState({saving: 'error'});
                }
            });
    };

    render() {
        const {t, theme, classes, viewMode, hasSelected, loadList, toggleViewMode, currentDir, loadParent} = this.props;

        return (
            <React.Fragment>
                <div className={classes.wrapper} style={{border: '1px solid ' + theme.textColorLight}}>
                    <p style={{fontFamily: theme.monospace, margin: 0, display: 'flex'}}>
                        {currentDir ? (
                            <React.Fragment>
                                <button onClick={loadParent}
                                ><MdSubdirectoryArrowRight size={'1.5em'} color={theme.textColor} style={{transform: 'rotate(180deg)'}}/></button>
                                {currentDir}
                            </React.Fragment>
                        ) : '/'}
                    </p>
                    <button className={classes.btn} style={{marginLeft: 'auto'}} onClick={() => loadList(currentDir)}><MdAutorenew size={'1.5em'} color={theme.textColor}/></button>
                    <button className={classes.btn} onClick={toggleViewMode}>{
                        'list' === viewMode ?
                            <MdViewModule size={'1.5em'} color={theme.textColor}/> :
                            <MdViewHeadline size={'1.5em'} color={theme.textColor}/>
                    }</button>
                    {!hasSelected ?
                        <button className={classes.btn} onClick={() => this.setState({openAddDir: !this.state.openAddDir})}><MdCreateNewFolder size={'1.5em'} color={theme.textColor}/></button> : null}
                </div>

                <Wrapper className={classes.wrapperAddDir} withParent={false} pose={this.state.openAddDir && !hasSelected ? 'visible' : 'hidden'}>
                    <InputText onChange={this.handleChange}
                               onKeyUp={this.enterCreateDir}
                               value={this.state.newDir}
                               style={{width: 'auto', flexGrow: 2}}
                               placeholder={t('enter-new-dir')}/>
                    <ButtonSmall onClick={this.createDir}>{t('create-dir')} {this.state.saving ?
                        ('progress' === this.state.saving || 'error' === this.state.saving ?
                            <React.Fragment>
                                <Loading style={{
                                    wrapper: {margin: 0},
                                    item: ('error' === this.state.saving ? {borderColor: theme.errorColor} : {}),
                                }}/>

                            </React.Fragment> :
                            ('success' === this.state.saving ?
                                <MdDone/> : null))
                        : null}</ButtonSmall>
                </Wrapper>
            </React.Fragment>
        );
    }
}

export default withNamespaces('file-explorer')(withPusher(withTheme(injectSheet(theming)(ControlBar))));