import _ from 'lodash';
import { ActionTypes, ApiStatuses } from 'constants/Common';
import dispatcher from 'dispatcher';
import { RouteTiming } from 'lib/rum';

function getApiStatus(response) {
    if (response) {
        if (!_.get(response, 'state.session')) {
            return ApiStatuses.UNAUTHORIZED;
        }

        if (_.get(response, 'state.unsafe')) {
            return ApiStatuses.UNSAFE;
        }
    }

    const globalError = _.get(window.ya, 'connect.initial.error.code');

    if (globalError) {
        return globalError;
    }

    return ApiStatuses.OK;
}

let appStarted;

export function start() {
    if (document.body.classList.contains('loaded')) {
        appStarted = true;
    }

    if (!appStarted) {
        document.body.className = 'loading';
        appStarted = true;
    }

    RouteTiming.lock();
    dispatcher.dispatch(ActionTypes.START_PROCESS);
}

export function succeed(response, partial) {
    if (!response) {
        dispatcher.dispatch(ActionTypes.RECEIVE_REQUEST_DATA, {});

        return;
    }

    const status = getApiStatus(response);

    dispatcher.dispatch(ActionTypes.RECEIVE_REQUEST_DATA,
        { response, status });

    if (status === ApiStatuses.OK && response) {
        dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);
    }

    if (!partial) {
        dispatcher.dispatch(ActionTypes.TRANSITION_COMPLETED);
        RouteTiming.unlock();
    }
}

export function fail(status, partial) {
    dispatcher.dispatch(ActionTypes.RECEIVE_REQUEST_DATA,
        { status });

    if (!partial) {
        dispatcher.dispatch(ActionTypes.TRANSITION_COMPLETED);
        RouteTiming.unlock();
    }
}

export function succeedAll(responses) {
    responses.forEach(response => succeed(response, true));
    dispatcher.dispatch(ActionTypes.TRANSITION_COMPLETED);
    RouteTiming.unlock();
}
