import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import StoreMixin from 'lib/StoreMixin';

import ApplicationStore from 'stores/Application';
import UserStore from 'stores/Users';
import DepartmentStore from 'stores/Departments';

import Department from 'components/Department';
import User from 'components/User';
import EmptyDepartment from './EmptyDepartment';

const APP_STATE_TYPES = ['', 'departments', 'users'];

const DepartmentLayout = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        return { key: this.hashCode() };
    },

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

    render() {
        const appStateType = ApplicationStore.getStateType();
        const displayedObject = ApplicationStore.getPrimaryObject();

        if (APP_STATE_TYPES.indexOf(appStateType) === -1) {
            return null;
        }

        if (appStateType === 'departments') {
            const department = DepartmentStore.get(displayedObject.id);

            // если root и если пустой и если оутстафф, то рисуем заглушку
            if (department && department.isOutstaff() && department.isRoot() && department.isEmpty()) {
                return (
                    <EmptyDepartment type="outstaff" />
                );
            }
        }

        const sections = ApplicationStore.getObjectChain()
            .map(item => {
                switch (item.type) {
                    case 'department':
                        return <Department id={item.id} key={`department-${item.id}`} />;
                    case 'user':
                        return <User id={item.id} key={`user-${item.id}`} />;
                }

                return null;
            });

        return (
            <div className="department-layout section-layout">
                {sections}
            </div>
        );
    },

});

export default DepartmentLayout;
