/**
 * Компонент, отвечающий за отображение заголовка страницы
 */

import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import StoreMixin from 'lib/StoreMixin';
import ApplicationStore from 'stores/Application';
import { i18n } from 'lib/i18n';

import UserStore from 'stores/Users';
import DepartmentStore from 'stores/Departments';
import GroupStore from 'stores/Groups';

const DEFAULT_TITLE = i18n('sections.admin');
const TITLE_POSTFIX = ` — ${DEFAULT_TITLE}`;

const SECTION_TITLE_MAP = {
    groups:
        i18n('sections.groups._title'),
    'groups/member':
        `${i18n('sections.groups._title')} / ${i18n('sections.groups.member')}`,
    'groups/admin':
        `${i18n('sections.groups._title')} / ${i18n('sections.groups.admin')}`,
    profile:
        i18n('sections.organization_profile'),
    dns:
        i18n('sections.admin_settings.dns'),
    customization:
        i18n('sections.admin_settings.organization._title'),
    'customization/domain':
        i18n('sections.admin_settings.organization.domain'),
    'customization/mail':
        i18n('sections.admin_settings.organization.mail'),
    'customization/import':
        i18n('sections.admin_settings.organization.import'),
    'customization/admins':
        i18n('sections.admin_settings.organization.admins'),
    'customization/general':
        i18n('sections.admin_settings.organization.general'),
};

function getTitle() {
    const displayedObject = ApplicationStore.getPrimaryObject();
    const stateType = ApplicationStore.getStateType();

    let title = SECTION_TITLE_MAP[stateType];

    if (displayedObject) {
        switch (displayedObject.type) {
            case 'user': {
                const user = UserStore.get(displayedObject.id);

                title = user ? user.getName() : null;
                break;
            }

            case 'department': {
                const department = DepartmentStore.get(displayedObject.id);

                title = department ? department.getName() : null;
                break;
            }

            case 'group': {
                const group = GroupStore.get(displayedObject.id);

                title = group ? group.getName() : null;
                break;
            }
        }
    }

    return title ? title + TITLE_POSTFIX : DEFAULT_TITLE;
}

const PageTitle = React.createClass({

    mixins: [PureRenderMixin, StoreMixin],

    getStoreState() {
        return { title: getTitle() };
    },

    componentDidMount() {
        this.subscribe([
            ApplicationStore,
            UserStore,
            DepartmentStore,
            GroupStore,
        ]);
    },

    render() {
        document.title = this.state.title;

        return null;
    },
});

export default PageTitle;
