import React from 'react';
import classSet from 'classnames';

import StoreMixin from 'lib/StoreMixin';
import Url from 'lib/Url';
import { i18n } from 'lib/i18n';

import ApplicationStore from 'stores/Application';
import UserStore from 'stores/Users';
import DepartmentStore from 'stores/Departments';
import GroupStore from 'stores/Groups';
import Link from 'ui/Link';

import './index.css';

const IGNORED_SECTIONS = [
    'subscription', 'customization', 'resources',
];

const GROUP_SUBSECTION_MAP = {
    all: i18n('sections.groups.all'),
    admin: i18n('sections.groups.admin'),
    member: i18n('sections.groups.member'),
};

const SECTION_MAP = {
    profile: {
        name: i18n('sections.organization_profile'),
        url: Url.getContextPath('profile'),
    },
    domains: {
        name: i18n('sections.customization.domains'),
        url: Url.getContextPath('domains'),
    },
    domain: {
        name: i18n('sections.customization.domain'),
        url: Url.getContextPath('domain'),
    },
    customization: {
        name: i18n('sections.customization._title'),
        url: Url.getContextPath('customization'),
        disabled: true,
    },
    'customization/import': {
        name: i18n('sections.customization.import'),
        url: Url.getContextPath('customization', 'import'),
    },
    'customization/admins': {
        name: i18n('sections.customization.admins'),
        url: Url.getContextPath('customization', 'admins'),
    },
    'customization/dns': {
        name: i18n('sections.customization.dns'),
        url: Url.getContextPath('customization', 'dns'),
    },
    'customization/general': {
        name: i18n('sections.customization.general'),
        url: Url.getContextPath('customization', 'general'),
    },
    'customization/wiki': {
        name: i18n('sections.services.wiki'),
        url: Url.getContextPath('customization', 'wiki'),
    },
    'customization/tracker': {
        name: i18n('sections.services.tracker'),
        url: Url.getContextPath('customization', 'tracker'),
    },
    'customization/mail': {
        name: i18n('sections.services.mail'),
        url: Url.getContextPath('customization', 'mail'),
    },
    'customization/mail/lost': {
        name: i18n('lost_mail.title'),
        url: Url.getContextPath('customization', 'mail', 'lost'),
    },
    'customization/mail/protocols': {
        name: i18n('mail_protocol.title'),
        url: Url.getContextPath('customization', 'mail', 'protocols'),
    },
    'customization/mail/signature': {
        name: i18n('mail_signature.title'),
        url: Url.getContextPath('customization', 'mail', 'signature'),
    },
    'customization/mail/todo': {
        name: i18n('to_do.title'),
        url: Url.getContextPath('customization', 'mail', 'todo'),
    },
    'customization/mail/dkim': {
        name: i18n('sections.customization.dkim'),
        url: Url.getContextPath('customization', 'mail', 'dkim'),
    },
};

function getChainItem(chainObject) {
    let store;
    let url;

    switch (chainObject.type) {
        case 'user':
            store = UserStore;
            url = Url.getUserPath(chainObject.id);
            break;

        case 'department':
            store = DepartmentStore;
            url = Url.getDepartmentPath(chainObject.id);
            break;

        case 'group':
            store = GroupStore;
            url = Url.getGroupPath('auto', chainObject.id);
            break;

        case 'domain':
            return {
                name: chainObject.id,
                url: Url.getDomainSettingsPath(chainObject.id),
            };
    }

    if (store) {
        const storedObject = store.get(chainObject.id);

        if (storedObject) {
            return { name: storedObject.getName(), url };
        }
    }
}

const Breadcrumbs = React.createClass({

    mixins: [StoreMixin],

    getStoreState() {
        return {};
    },

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

    _getItems() {
        const section = ApplicationStore.getSectionName();

        if (IGNORED_SECTIONS.indexOf(section) !== -1) {
            return [];
        }

        const objectChain = ApplicationStore.getObjectChain();
        const primaryType = ApplicationStore.getPrimaryType();
        let items = [];

        switch (primaryType) {
            case 'root':
            case 'departments':
            case 'users':
                items = objectChain.map(getChainItem);
                break;

            case 'groups': {
                const subsection = ApplicationStore.getSubsectionName();

                items = objectChain.map(getChainItem);

                // подраздел команд
                if (subsection !== 'all' && GROUP_SUBSECTION_MAP[subsection]) {
                    items.unshift({
                        name: GROUP_SUBSECTION_MAP[subsection],
                        url: Url.getGroupListPath('auto'),
                    });
                }

                // ссылка на все команды
                items.unshift({
                    name: GROUP_SUBSECTION_MAP.all,
                    url: Url.getGroupListPath('all'),
                });
                break;
            }

            default: {
                const sections = ApplicationStore.getSections();
                const sectionValues = sections.map(item => item.value);

                sections.forEach((sectionItem, index) => {
                    const chain = sectionValues.slice(0, index + 1);
                    const id = chain.join('/');
                    let item = SECTION_MAP[id];

                    if (sectionItem.object) {
                        item = getChainItem(sectionItem.object);
                    } else if (!item && sectionItem.value) {
                        item = {
                            name: i18n(`navigation.${chain.join('.')}._title`) || sectionItem.value,
                            url: Url.getContextPath.apply(Url, chain),
                        };
                    }

                    if (item && !item.disabled) {
                        items.push(item);
                    }
                });
            }
        }

        return items.filter(Boolean);
    },

    _renderItems() {
        const items = this._getItems();

        return items.map((item, index) => {
            const className = classSet({
                breadcrumbs__item: true,
                breadcrumbs__item_active: index === items.length - 1,
            });

            return (
                <div className={className} key={index}>
                    <Link
                        to={item.url}
                        className="breadcrumbs__link"
                        title={item.name}
                        metrika={['Клик в хлебные крошки']}
                    >
                        {item.name}
                    </Link>
                </div>
            );
        });
    },

    render() {
        const items = this._renderItems();

        if (!items.length) {
            return null;
        }

        return <div className="breadcrumbs">{items}</div>;
    },

});

export default Breadcrumbs;
