import React from 'react';
import {withNamespaces} from 'react-i18next';

import {injectSheet, withTheme} from '../../lib/theme';
import Explorer from "./Explorer";
import {ButtonSmall} from "../Form";

const theming = (theme) => ({
    wrapper: {},
    wrapperInner: {
        maxHeight: '300px',
        overflowY: 'auto'
    },
    qty: {
        fontSize: '0.875rem',
        margin: '0 0 ' + theme.gutter.base * 2 + 'px 0'
    }
});

class ExplorerSelect extends React.Component {

    state = {
        selected: {
            dir: {},
            file: {}
        }
    };

    clearSelect = () => {
        this.setState({
            selected: {
                dir: {},
                file: {}
            }
        });
    };

    onSelect = (type, id, shouldAdd) => {
        const multiple = this.props.multiple;
        let selected = {...this.state.selected};

        if(shouldAdd) {
            if(!multiple) {
                // todo: add through constant exports
                selected['file'] = {};
                selected['dir'] = {};
            }
            selected[type][id] = true;
            this.setState({selected});
        } else if(selected[type][id]) {
            delete selected[type][id];
            this.setState({selected});
        }
    };

    render() {
        const {
            classes, t,
            selectFile, selectDir,
            multiple, choosenFiles,
            save
        } = this.props;

        let qty = Object.keys(this.state.selected.dir).length + Object.keys(this.state.selected.file).length;

        return (
            <div className={classes.wrapper}>
                <div className={classes.wrapperInner}>
                    <Explorer onSelect={this.onSelect}
                              clearSelect={this.clearSelect}
                              hasSelected={0 < qty}
                              selected={this.state.selected}
                              selectFile={selectFile}
                              selectDir={selectDir}
                              multiple={multiple}
                    />
                </div>

                <p className={classes.qty}>{0 < qty ? t('selected-qty') + ' ' + qty : t('nothing-selected')}</p>

                {0 < qty ?
                    <div className={classes.controls}>
                        <ButtonSmall onClick={() => {
                            save(this.state.selected)
                        }}>{!multiple ?
                            0 < choosenFiles.length ? t('replace-with-selected') : t('choose-selected-single')
                            : t('choose-selected')}</ButtonSmall>
                    </div> : null}
            </div>
        );
    }
}

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