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

import {withTheme} from "../../lib/theme";
import {Select} from "../Form";
import {withBackend} from "../../feature/BackendConnect";
import {withAuthPermission} from "../../feature/AuthPermission";


class HookSwitchSelectBase extends React.Component {
    render() {
        const {
            theme, onSwitched, switchHook, hook_active, hooks,
            isAllowedHook
        } = this.props;

        return (
            <Select
                onChange={(e) => {
                    if(switchHook(e.target.value) && onSwitched) {
                        onSwitched();
                    }
                }}
                value={hook_active.id}
                style={{
                    background: theme.bgPage,
                    border: '1px solid ' + theme.textColorLight,
                    color: theme.textColor,
                }}
            >
                {hooks ?
                    Object.keys(hooks).map((id) => (
                        isAllowedHook(id) ? <option key={id} value={id}>{hooks[id].label}</option> : null
                    )) : null
                }
            </Select>
        );
    }
}

const HookSwitchSelect = withAuthPermission(withBackend(withTheme(HookSwitchSelectBase)));

class HookSwitchBase extends React.Component {
    render() {
        const {
            theme, t, onSwitched, hooks_qty, hook_active
        } = this.props;

        return (
            <div style={{marginBottom: theme.gutter.base * 2 + 'px'}}>
                <div style={{marginBottom: hooks_qty < 2 ? 0 : theme.gutter.base * 2 + 'px'}}>
                    {hooks_qty < 1 ?
                        <p style={{marginBottom: '3px'}}>{t('backend-connect.no-hook')}</p> :
                        <p style={{marginBottom: '3px'}}>{t('backend-connect.active-hook')} <em>{hook_active.label} ({hook_active.id})</em></p>}
                </div>
                {hooks_qty < 2 ? null :
                    <div style={{}}>
                        <label style={{marginBottom: theme.gutter.base * 2 + 'px'}}>{t('backend-connect.switch-hook')}</label>
                        <HookSwitchSelect onSwitched={onSwitched}/>
                    </div>}
            </div>
        );
    }
}

const HookSwitch = withNamespaces('common')(withBackend(withTheme(HookSwitchBase)));

export {HookSwitch, HookSwitchSelect};