import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Input } from 'neatui';

class RangeBar extends PureComponent {
	constructor (props, context) {
        super(props, context);
        this.state = {
            value: 0,
            readonly: false
        };
    }

    componentDidMount() {
        const {value, readonly} = this.props;
        this.setState({
            value,
            readonly
        });

        this.rangeInput.style.backgroundSize = '0% 100%';
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            value: nextProps.value,
            readonly: nextProps.readonly
        });
        this.rangeInput.style.backgroundSize = `${nextProps.value}% 100%`;
    }

    onRangeChange(e, value) {
        const { onChange } = this.props;
        this.rangeInput.style.backgroundSize = `${value}% 100%`;
        if (onChange) onChange(value);
        this.setState({
            value
        });
    }

    getRangeInput = (el) => {
        this.rangeInput = el;
    };

    render() {
        const { value, readonly } = this.state;
        return <Input type="range"
                      defaultValue={ value }
                      autoComplete="off"
                      onChange={(e, cValue) => this.onRangeChange(e, cValue)}
                      inputRef={this.getRangeInput}
                      disabled={readonly}
                      className="rate-range-bar"/>
    }

}

RangeBar.propTypes = {
    value: PropTypes.number,
    readonly: PropTypes.bool,
    onChange: PropTypes.func
};

RangeBar.defaultProps = {
    value: 0,
    readonly: false,
    onChange: null
};

export default RangeBar;
