import React from 'react';
import { Switch, Route } from 'react-router-dom';
import buildUrl from '@connect/url-placeholders';
import TabLink from 'components2/TabLink';
import ServiceSubscribers from 'components2/ServiceSubscribers';
import ServiceRequests from 'components2/ServiceRequests';
import { PricingStore, ServiceStore, ServiceRequestsStore, ConfigStore } from 'lib2/stores';
import getService from 'lib2/getService';
import isCurrentRoute from 'lib2/isCurrentRoute';
import directory from 'api2/directory';
import { i18n } from 'i18n2';

function getRequestCount(serviceSlug) {
    let list = ServiceRequestsStore.get([serviceSlug, 'list']);

    if (Array.isArray(list)) {
        return list.length;
    }

    return ServiceRequestsStore.get([serviceSlug, 'count']);
}

function getServiceTabLink(serviceSlug) {
    return buildUrl(ConfigStore.get(['ui', 'serviceTabLink', serviceSlug]), {
        tld: ConfigStore.get('app.tld'),
    });
}

export default class SubscriptionServiceTabs extends React.PureComponent {
    constructor(props) {
        super(props);

        this.state = {};

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

    componentDidMount() {
        this._update();

        this._storeListeners = [
            ServiceRequestsStore.onChange(this._update),
            ServiceStore.onChange(this._update),
        ];

        this._init();
    }

    componentWillUnmount() {
        this._storeListeners.forEach(listener => listener.remove());
    }

    componentDidUpdate(prevProps) {
        if (this.props.serviceSlug !== prevProps.serviceSlug) {
            this._update();
            this._init();
        }
    }

    _init() {
        let { serviceSlug, tabs = {} } = this.props;
        let { enabled, ready } = getService(serviceSlug);

        let shouldFetchRequestCount = tabs.requests &&
            enabled &&
            ready &&
            getRequestCount(serviceSlug) === undefined &&
            // оптимизация:
            // не нужно узнавать количество заявок отдельным запросом,
            // находясь на роуте вкладки с запросами, потому что
            // эта вкладка сама запросит полный список заявок
            !isCurrentRoute(`/portal/services/${serviceSlug}/requests`);

        if (shouldFetchRequestCount) {
            // минимальный запрос для подсчёта заявок:
            // без fields, с минимальным per_page
            directory
                .send('GET', `/v11/subscription/services/${serviceSlug}/licenses/request/`, {
                    query: { per_page: 1 },
                })
                .then(({ ok, body }) => {
                    if (ok && body) {
                        ServiceRequestsStore.set([serviceSlug, 'count'], body.total);
                    }
                });
        }

        this._fetchPricing();
    }

    _update() {
        let { serviceSlug } = this.props;
        let { enabled, ready } = getService(serviceSlug);

        this.setState({
            enabled,
            ready,
            requestCount: getRequestCount(serviceSlug),
        });
    }

    _fetchPricing(mode) {
        // после обновления подписок Директория немгновенно обновляет
        // количество подписчиков в прайсинге, поэтому запрашиваем с задержкой
        setTimeout(() => {
            directory.send('GET', '/v11/subscription/pricing/')
                .then(({ body }) => {
                    PricingStore.mergeState(body);
                });
        }, mode === 'delayed' ? 2000 : 0);
    }

    render() {
        let { serviceSlug, tabs = {}, subscriberSearchType } = this.props;
        let { enabled, ready, requestCount } = this.state;

        if (!Object.values(tabs).filter(Boolean).length || !enabled || !ready) {
            return null;
        }

        return (
            <React.Fragment>
                <TabLink.Group>
                    {tabs.subscriptions && (
                        <TabLink url={`/portal/services/${serviceSlug}`}>
                            {i18n('licenses.tabs.subscriptions')}
                        </TabLink>
                    )}
                    {tabs.requests && (
                        <TabLink url={`/portal/services/${serviceSlug}/requests`}>
                            {i18n('license_requests.tab_title')}
                            {requestCount && <TabLink.CounterBadge>{requestCount}</TabLink.CounterBadge>}
                        </TabLink>
                    )}
                    {tabs.link && (
                        <TabLink url={getServiceTabLink(serviceSlug)}>
                            {i18n('licenses.tabs.settings')}
                            <TabLink.ExternalLinkBadge />
                        </TabLink>
                    )}
                </TabLink.Group>
                <Switch>
                    {tabs.subscriptions && (
                        <Route exact path={`/portal/services/${serviceSlug}`}>
                            <TabLink.Pane>
                                <ServiceSubscribers
                                    serviceSlug={serviceSlug}
                                    subscriberSearchType={subscriberSearchType}
                                    onUpdate={() => this._fetchPricing('delayed')}
                                />
                            </TabLink.Pane>
                        </Route>
                    )}
                    {tabs.requests && (
                        <Route exact path={`/portal/services/${serviceSlug}/requests`}>
                            <TabLink.Pane>
                                <ServiceRequests
                                    serviceSlug={serviceSlug}
                                    onUpdate={() => this._fetchPricing('delayed')}
                                />
                            </TabLink.Pane>
                        </Route>
                    )}
                </Switch>
            </React.Fragment>
        );
    }
}
