import _get from 'lodash/get';
import React from 'react';
import Header from '@connect/react-header';
import buildUrl from '@connect/url-placeholders';
import OrgSwitch from 'components2/OrgSwitch';
import SearchInput from 'components2/SearchInput';
import { ConfigStore, SessionStore, OrgStore, ServiceStore } from 'lib2/stores';
import getServices from 'lib2/getServices';
import getOrganization from 'lib2/getOrganization';
import { i18n } from 'i18n2';
import User2 from './User2';
import './index.css';

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

        this.state = {
            busy: true,
        };

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

    componentDidMount() {
        this._update();

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

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

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

        let orgLogo = getOrganization().logo;

        this.setState({
            busy: orgLogo === undefined,
            customLogo: _get(orgLogo, 'orig.url'),
            services: getServices().filter(({ enabled, ready }) => enabled && ready),
        });
    }

    render() {
        let { cls, hasSearchBox } = this.props;
        let { customLogo, services, busy } = this.state;

        let logoUrl = ConfigStore.get('ui.logo');

        let user = {
            ...SessionStore.get('current'),
            ...SessionStore.get('user'),
        };

        return (
            <Header
                busy={busy}
                cls={cls}
            >
                <Header.LogoMenu
                    items={services}
                />
                <Header.MainLogo
                    src={customLogo || buildUrl(logoUrl, { text: i18n('related_services.yandex') })}
                    custom={Boolean(customLogo)}
                />
                <Header.SecondaryLogo
                    src={buildUrl(logoUrl, { text: i18n('related_services.connect') })}
                    url="/portal/home"
                />
                <OrgSwitch />
                <Header.FlexSpace />
                {hasSearchBox && (
                    <SearchInput
                        type="navigation"
                        showSearchIcon
                    />
                )}
                <User2
                    cls="user2-widget"
                    user={user}
                />
            </Header>
        );
    }
}
