import * as React from 'react'
import { Row, RadioButton, Divider } from '../web'
import { RadioGroupProps, RadioOption } from '../interfaces'

const styles = require('../../src/styles/components/radio.scss')

export class RadioGroup extends React.Component<RadioGroupProps, any> {

    public render() {
        return (
            <Row column="xs" row="sm" justify="space-between">
                {this.props.options.map(o =>
                    <RadioButton
                        isSelected={this.isSelected(o)}
                        onChange={this.mkHandleChange(o.label)}
                        key={o.label}
                        name={this.props.formName}
                        label={o.label}
                        value={o}
                        img={o.img} />)}
            </Row>
        )
    }

    /**
     * Radio options have the exact same problem as select options
     * You can't set an object as a radio option's value, so inorder to get round this
     * you need to find the object by id and then pass that in as the value
     */
    private mkHandleChange = (id: string): any =>
        (e: React.SyntheticEvent<any>) => {
            const selected = this.props.options.find(o => o.label === id)
            this.props.onChange(selected)
        }

    private isSelected(option: RadioOption) {
        return this.props.selected && this.props.selected.label === option.label
    }
}
