import { MenuItem, Select, FormControl, InputLabel, withStyles } from '@material-ui/core';
import React from 'react';

const styles = theme => ({
    root: {
      display: 'flex',
      flexWrap: 'nowrap' as any,
    },
    formControl: {
      margin: theme.spacing.unit,
      minWidth: 250,
      maxWidth: 500
    },
    selectEmpty: {
      marginTop: theme.spacing.unit * 2,
      minWidth: 200
    }
})
export interface SpecSelectorState {
    specs: any[]
    selectedSpecId?: string
}
export interface SpecSelectorProps {
    config: any
    onSelected(spec: any)
}
class DataProcessingSpecSelector extends React.Component<any, SpecSelectorState> {
    state: SpecSelectorState = {
        specs: []
    }
    async componentWillMount() {
        const base = this.props.config && this.props.config.dataprocessingAPI
        const endPoint = `${base}/dpspecs`

        /** Fetch the data processing */
        const response = await fetch(endPoint, {
            method: 'GET', 
            headers: {
                Authorization: `Bearer ${this.props.config.accessToken}`
            }
        })
        const specs = await response.json() || []
        this.setState({specs})
    }

    render() {
        const { classes } = this.props
        const { selectedSpecId } = this.state

        return (
        <FormControl>
            <InputLabel htmlFor="dpspec-select">Data Processing Spec</InputLabel>
            <Select 
                className={classes.selectEmpty}
                inputProps={{
                    id: "dpspec-select"
                }}
                onChange={event => { 
                    this.setState({selectedSpecId: event.target.value})
                    this.props.onChange(event) 
                }}
                value={selectedSpecId || ""}
            >
                {this.state.specs.map((s, idx) => <MenuItem key={s.id} value={s.id}> {`${s.data}: ${s.action} (${s.id})`} </MenuItem>)}                    
            </Select>
        </FormControl>
        )
    }
}

const styled: React.ComponentType<any> = withStyles(styles)(DataProcessingSpecSelector)
export { styled as DataProcessingSpecSelector}
