import React from 'react';
import block from 'bem-cn';
import ServiceStatusPolling from 'lib2/ServiceStatusPolling';
import directory from 'api2/directory';
import metrika from 'api2/metrika';
import { PricingStore, ServiceStore } from 'lib2/stores';
import getServices from 'lib2/getServices';
import { i18n } from 'i18n2';
import { RouteTiming } from 'lib2/rum';
import DashboardCard from 'components2/DashboardCard';
import './index.css';
import './notifications.css';

const b = block('dashboard');

class Dashboard extends React.PureComponent {
    constructor(props) {
        super(props);

        this.state = {};
        this._update = this._update.bind(this);
    }

    componentDidMount() {
        RouteTiming.end();

        this._update();
        this._serviceStoreListener = ServiceStore.onChange(this._update);

        directory.send('GET', '/v11/subscription/pricing/').then(({ body }) => {
            PricingStore.mergeState(body);
        });

        ServiceStatusPolling.start('delayed');
    }

    componentWillUnmount() {
        this._unmounted = true;
        this._serviceStoreListener.remove();

        ServiceStatusPolling.stop();
    }

    _update() {
        if (this._unmounted) {
            return;
        }

        let services = getServices();

        if (!this.state.inited && ServiceStore.get('order') !== undefined) {
            metrika.send(
                'Дашборд',
                'Показ плитки',
                services.map(({ available, slug }) => available && slug).filter(Boolean)
            );

            this.setState({
                inited: true,
            });
        }

        this.setState({
            services,
        });
    }

    render() {
        let { services } = this.state;

        if (!services || !services.length) {
            return null;
        }

        return (
            <div className={b('tile').mix(this.props.cls)}>
                <div className={b('heading')}>
                    {i18n('dashboard.heading')}
                </div>
                <div className={b('cards')}>
                    {services.map(service => service.available && (
                        <DashboardCard
                            serviceSlug={service.slug}
                            key={JSON.stringify(service)}
                        />
                    ))}
                </div>
            </div>
        );
    }
}

export default Dashboard;
