import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { block } from 'bem-cn';
import Loader from 'ui-components/lib/Loader';
import StoreMixin from 'lib/StoreMixin';
import { i18n } from 'lib/i18n';
import { Service } from 'lib/services';
import Notifications from 'components/Notifications';

import ApplicationStore from 'stores/Application';
import AuthStore from 'stores/Auth';
import DomainStore from 'stores/Domains';
import ServiceStore from 'stores/Services';
import PermissionStore from 'stores/Permissions';
import SubscriptionStore from 'stores/Subscription';

import Header from 'components/Header';
import Footer from 'components/Footer';
import ModalBox from 'components/ModalBox';
import PaymentNotification from 'components/PaymentNotification';
import AutomigrationSurvey from 'components/PinnedNotification/AutomigrationSurvey';
import CustomSurvey from 'components/PinnedNotification/CustomSurvey';

import SubscriptionActions from 'actions/Subscription';
import SenderActions from 'actions/Sender';
import BunkerActions from 'actions/Bunker';
import Metrika from 'lib/metrika';
import SERVICE_ITEMS from './serviceList';

import Card from './Card';

import './index.css';
import './notifications.css';

function getProp(item, propName) {
    return typeof item[propName] === 'function' ? item[propName]() : item[propName];
}

const bDashboard = block('dashboard');

const Dashboard = React.createClass({

    mixins: [PureRenderMixin, StoreMixin],

    getStoreState() {
        return {
            services: Service.getList(SERVICE_ITEMS),
            inProgress: ApplicationStore.isBusy(),
            // стейт должен зависеть от прав на редактирование структуры оргназиции
            // чтобы при изменении правильно отображалась иконка администрирования
            allowsOrganizationStructureEditing: PermissionStore.allowsOrganizationStructureEditing(),
        };
    },

    componentDidMount() {
        this.subscribe([ApplicationStore, DomainStore, ServiceStore, PermissionStore, SubscriptionStore]);
        document.body.className = 'loaded connect-app';
        document.body.dataset.section = 'connect-dashboard';

        SERVICE_ITEMS.forEach(item => {
            if (getProp(item, 'available')) {
                const isService = item.id.indexOf('service.') === 0;

                if (!isService || Service.isAvailable(item.id.replace('service.', ''))) {
                    Metrika.send('Дэшборд', item.metrika, 'Плитка показана');
                }
            }
        });

        SenderActions.showSubscriptionForm();

        // Выгружаю данные из бункера
        BunkerActions.fetchNodes();
        SubscriptionActions.trackServiceStatus();
    },

    componentWillUnmount() {
        SubscriptionActions.stopServiceStatusTracking();
    },

    _renderItems() {
        return this.state.services.map(this._renderItem);
    },

    _renderItem(itemProps) {
        if (itemProps.available !== undefined && !itemProps.available) {
            return null;
        }

        return (
            <Card key={itemProps.id} {...itemProps} />
        );
    },

    render() {
        return (
            <div className={bDashboard({}).mix('layout-container')}>
                <AutomigrationSurvey />
                <CustomSurvey />
                <Header searchEnabled={!AuthStore.isExternalAdmin()} />
                <PaymentNotification />
                <Notifications />
                <div className={bDashboard('tile')}>
                    <p className={bDashboard('heading')}>{i18n('dashboard.heading')}</p>
                    <div className={bDashboard('items')}>
                        {this._renderItems()}
                    </div>
                </div>
                <Footer showDownloads />
                <Loader visible={this.state.inProgress} />
                <ModalBox />
            </div>
        );
    },

});

export default Dashboard;
