import PropTypes from 'prop-types';
import React from 'react';

import CaptchaActions from 'actions/Captcha';
import CaptchaStore from 'stores/Captcha';
import StoreMixin from 'lib/StoreMixin';

import { i18n } from 'lib/i18n';
import Captcha from './Captcha';

const CaptchaContainer = React.createClass({

    mixins: [StoreMixin],

    getInitialState() {
        return {
            loading: false,
        };
    },

    getStoreState() {
        return {
            captchaSrc: CaptchaStore.getSrc(),
        };
    },

    componentDidMount() {
        this.subscribe([CaptchaStore]);

        this._refreshCaptcha();
    },

    _onChange(text) {
        this.props.onChange(text);
    },

    _onRefresh() {
        this._refreshCaptcha();
    },

    _refreshCaptcha() {
        this.setState({ loading: true });

        CaptchaActions.refresh()
            .finally(() => {
                this.setState({ loading: false });
            });
    },

    render() {
        const { captchaSrc, loading } = this.state;
        const { text, onChange } = this.props;

        return (
            <Captcha
                src={captchaSrc}
                text={text}
                onChange={onChange}
                onRefresh={this._onRefresh}
                loading={loading}
                labels={i18n('common.captcha')}
            />
        );
    },

});

CaptchaContainer.propTypes = {
    text: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
};

export default CaptchaContainer;
