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

import {CounterText} from '../CounterText';

export class StoreCounterText extends React.Component {
    static propTypes = {
        ...CounterText.propTypes,
        store: PropTypes.object.isRequired
    };

    constructor(props, context) {
        super(props, context);

        this.state = {
            counter: this.props.store.getFilteredCount()
        };

        this.onStoreChange = () => {
            if (this.unmounted) {
                return;
            }
            this.setState({
                counter: this.props.store.getFilteredCount()
            });
        };
    }

    componentDidMount() {
        this.props.store.on('change', this.onStoreChange, this);
    }

    componentWillReceiveProps(nextProps) {
        this.props.store.off('change', this.onStoreChange);
        nextProps.store.on('change', this.onStoreChange, this);
    }

    componentWillUnmount() {
        this.unmounted = true;
        this.props.store.off('change', this.onStoreChange);
    }

    render() {
        return <CounterText {...this.props} counter={this.state.counter} />;
    }
}
