import _ from 'lodash';
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { block } from 'bem-cn';
import StoreMixin from 'lib/StoreMixin';
import storage from 'services/storage';

import PageTitle from 'components/PageTitle';
import ModalBox from 'components/ModalBox';
import Sidebar from 'components/Navigation/Sidebar';
import Footer from 'components/Footer';
import ServiceSidebar from 'components/ServiceSidebar';
import Header from 'components/Header';
import StatusBar from 'components/StatusBar';
import Notifications from 'components/Notifications';
import ReorgNotification from 'components2/ReorgNotification';
import AutomigrationSurvey from 'components/PinnedNotification/AutomigrationSurvey';
import CustomSurvey from 'components/PinnedNotification/CustomSurvey';
import Unknown from 'components/Unknown';
import Process from 'ui/Process';

import ApplicationStore from 'stores/Application';
import AuthStore from 'stores/Auth';
import OrganizationStore from 'stores/Organizations';
import DomainStore from 'stores/Domains';
import SenderActions from 'actions/Sender';
import BunkerActions from 'actions/Bunker';
import timer from 'lib/timer';
import { showUserAgreement } from './intro';

import './index.css';
import './scrollbar.css';
import './components.css';
import './table.css';

import plusActiveIcon from '../../../static/i/plus-active-solid-circle.svg';

const bApp = block('app');
const REQUEST_ERRORS = ['NOT_FOUND', 'UNSAFE'];

function prefetchImages() {
    (new Image()).src = plusActiveIcon;
}

const App = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        const hasOwnedDomains =
            OrganizationStore.hasOwnedDomains() ||
            DomainStore.hasOwnedDomains();
        const nextState = _.assign(ApplicationStore.getProcessState(), { hasOwnedDomains });

        if (!this.state || this.state.hasOwnedDomains === undefined) {
            nextState.hadOwnedDomains = hasOwnedDomains;
        }

        if (!this.state) {
            nextState.collapsed = storage.local.getValue('service_sidebar_collapsed') || false;
        }

        return nextState;
    },

    componentDidMount() {
        this.subscribe([ApplicationStore, OrganizationStore, DomainStore]);

        document.body.className = 'loaded connect-app';
        document.body.dataset.section = 'connect';

        timer.stop('first_run');

        // DIR-5042: Выпилить приветственные попапы в коннекте
        // showIntro();
        showUserAgreement();

        prefetchImages();

        // Форма для подписки на рассылку Коннекта
        SenderActions.showSubscriptionForm();

        // Выгружаю данные из бункера
        BunkerActions.fetchNodes();
    },

    componentWillUpdate(nextProps, nextState) {
        if (!this.state.hadOwnedDomains && nextState.hasOwnedDomains) {
            location.reload();
        }
    },

    onServiceSidebarToggle(collapsed) {
        this.setState({ collapsed });
    },

    render() {
        if (REQUEST_ERRORS.indexOf(ApplicationStore.getRequestStatus()) !== -1) {
            return <Unknown />;
        }

        const component = {};
        const adminMode = AuthStore.getViewMode() === 'admin';
        const servicePage = AuthStore.getViewMode() === 'services';

        if (adminMode) {
            component.sidebar = (
                <div className="app__sidebar">
                    <Sidebar />
                </div>
            );
        }

        if (servicePage) {
            component.serviceSidebar = (
                <div className="app__sidebar">
                    <ServiceSidebar onToggle={this.onServiceSidebarToggle} />
                </div>
            );

            component.footer = <Footer showDownloads />;
        }

        return (
            <div
                className={bApp({
                    'service-page': servicePage,
                    'sidebar-enabled': adminMode || servicePage,
                    'sidebar-collapsed': this.state.collapsed,
                })}
            >
                <PageTitle />
                <div className="app__header">
                    <CustomSurvey />
                    <AutomigrationSurvey />
                    <StatusBar />
                    <Header />
                    <ReorgNotification />
                </div>
                <div className={bApp('body')}>
                    {component.serviceSidebar}
                    {component.sidebar}
                    <div className="app__content">
                        <Notifications />
                        {this.props.children}
                        {!servicePage && <Process {...this.state} />}
                    </div>
                    {servicePage && <Process {...this.state} />}
                </div>
                {component.footer}
                <ModalBox />
            </div>
        );
    },

});

export default App;
