import React from 'react';
import { Spin } from 'lego-on-react';
import block from 'bem-cn';
import DocTitle from 'components2/DocTitle';
import ServiceSidebar from 'components2/ServiceSidebar';
import NotFound from 'components2/NotFound';
import getService from 'lib2/getService';
import hasPermission from 'lib2/hasPermission';
import ServiceStatusPolling from 'lib2/ServiceStatusPolling';
import { redirectToForbidden } from 'lib2/redirectToForbidden';
import getCloudPromoUrl from 'lib2/getCloudPromoUrl';
import isCloudPromoService from 'lib2/isCloudPromoService';
import { ServiceStore } from 'lib2/stores';
import { i18n } from 'i18n2';

import './index.css';

const b = block('service-page');

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

        this.state = {
            busy: true,
        };
    }

    componentDidMount() {
        this._update();
        this._serviceStoreListener = ServiceStore.onChange(() => this._update());

        ServiceStatusPolling.start('delayed');
    }

    componentWillUnmount() {
        this._serviceStoreListener.remove();

        ServiceStatusPolling.stop();
    }

    _update() {
        let service = getService(this.props.serviceSlug);

        if (service.available === false) {
            return redirectToForbidden();
        }

        // @see DIR-9977 DIR-10400
        if (isCloudPromoService(service)) {
            return window.location.assign(getCloudPromoUrl(service.slug));
        }

        if (service.available !== undefined) {
            this.setState({
                busy: false,
            });
        }

        this.setState({
            service,
            hashKey: JSON.stringify(service),
        });
    }

    render() {
        let { serviceSlug, children, cls } = this.props;
        let { busy, service, hashKey } = this.state;

        if (!service || !service.available) {
            return <NotFound />;
        }

        return (
            <div className={b({ slug: serviceSlug }).mix(cls)}>
                <DocTitle
                    text={`${service.name} @ ${i18n('common.full_main_title')}`}
                    key={`DocTitle-${hashKey}`}
                />
                {hasPermission('use_connect') && (
                    <ServiceSidebar
                        cls={b('sidebar')}
                        serviceSlug={serviceSlug}
                        key={`ServiceSidebar-${hashKey}`}
                    />
                )}
                <div className={b('content')}>
                    {busy ?
                        <Spin
                            progress
                            size="m"
                            position="center"
                        /> :
                        children}
                </div>
            </div>
        );
    }
}
