/**
 * Переключатель организаций
 */

import React from 'react';
import { block } from 'bem-cn';
import { Dropdown, Menu } from 'lego-on-react';
import ScrollArea from 'ui-externals/ScrollArea';
import StoreMixin from 'lib/StoreMixin';
import Metrika from 'lib/metrika';
import Url from 'lib/Url';
import { i18n } from 'lib/i18n';

import AuthStore from 'stores/Auth';
import OrganizationStore from 'stores/Organizations';
import ModalActions from 'actions/Modal';
import AddOrgForm from './AddOrgForm';

import './index.css';

const bOrgSwitch = block('organization-switch');

const OrgSwitch = React.createClass({

    mixins: [StoreMixin],

    getStoreState() {
        const orgId = AuthStore.getOrganizationId();
        const organizations = OrganizationStore.getAll();
        const options = organizations
            .map(organization => ({
                text: organization.name,
                val: organization.id,
            }))
            .sort((a, b) => {
                if (a.text === b.text) {
                    return 0;
                }

                return a.text > b.text ? 1 : -1;
            });

        return {
            orgId,
            orgName: OrganizationStore.getOrgName(orgId),
            available: AuthStore.isExternalAdmin() || OrganizationStore.getSize() > 1,
            options,
        };
    },

    componentDidMount() {
        this.subscribe([AuthStore, OrganizationStore]);
    },

    _setDropdownRef(ref) {
        if (ref) {
            this._dropdown = ref;
        }
    },

    _closeDropdownPopup() {
        if (this._dropdown) {
            // Это хак для того чтобы закрывать попап при клике по его содержимому
            this._dropdown._onOutsideClick();
        }
    },

    _onMenuItemClick(event, selectedValue) {
        const { orgId } = this.state;

        if (selectedValue && selectedValue !== orgId) {
            this._changeOrganization(selectedValue);
        }

        this._closeDropdownPopup();
    },

    _changeOrganization(orgId) {
        let retpath = location.pathname;

        // Если меняем организацию со страницы /forbidden
        // то перекидываем пользователя на дашборд
        if (retpath === Url.getPath(Url.Path.FORBIDDEN)) {
            retpath = Url.getPath(Url.Path.DASHBOARD);
        }

        Metrika.send('Смена текущей организации');
        location.href = Url.getOrganizationPath(orgId, Url.getReturnPath() || retpath);
    },

    _addOrganization() {
        this._closeDropdownPopup();

        ModalActions.open({
            title: i18n('organization_setup.new_org.title'),
            component: AddOrgForm,
        });
    },

    _renderPopupContent() {
        const { options, orgId } = this.state;

        return (
            <div className={bOrgSwitch('popup')}>
                <ScrollArea
                    className={bOrgSwitch('scroll-area').toString()}
                    minScrollSize={18}
                >
                    <Menu
                        theme="normal"
                        size="m"
                        type="radio"
                        width="max"
                        cls={bOrgSwitch('menu')}
                        val={orgId}
                        items={options}
                        onClick={this._onMenuItemClick}
                    />
                </ScrollArea>
                <div className={bOrgSwitch('add-org')} onClick={this._addOrganization}>
                    <span className={bOrgSwitch('add-org-caption')}>
                        {i18n('common.new_organization')}
                    </span>
                </div>
            </div>
        );
    },

    render() {
        const { available, orgName } = this.state;

        if (!available) {
            return null;
        }

        return (
            <Dropdown
                size="m"
                switcher="button2"
                theme="normal"
                width="max"
                cls={bOrgSwitch()}
                hasTick
                ref={this._setDropdownRef}
            >
                <Dropdown.Switcher>
                    <div className={bOrgSwitch('text')}>
                        {orgName}
                    </div>
                </Dropdown.Switcher>
                <Dropdown.Popup>
                    {this._renderPopupContent()}
                </Dropdown.Popup>
            </Dropdown>
        );
    },
});

export default OrgSwitch;
