import _ from 'lodash';
import { Promise } from 'rsvp';
import { ActionTypes } from 'constants/Common';
import { Statuses } from 'constants/Restore';
import dispatcher from 'dispatcher';
import restoreApi from 'api/org.restore';

export default {
    getCurrentOwner,
    trackStatus,
    stopStatusTracking,
    getStatus,
    checkOwnership,
    start,
};

function getCurrentOwner(domain) {
    return restoreApi.getCurrentOwner(domain)
        .then(response => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            return response.restore;
        })
        .catch(error => error.response);
}

const STATUS_TRACKING_PERIOD = 30000;

let statusTracking;
let nextCheck;

function trackStatus(restoreId) {
    if (statusTracking) {
        stopStatusTracking();
    }

    statusTracking = new Promise(resolve => {
        const check = () => {
            getStatus(restoreId)
                .then(data => {
                    if (_.get(data, 'current_check.state') === Statuses.IN_PROGRESS) {
                        nextCheck = setTimeout(check, STATUS_TRACKING_PERIOD);
                    } else {
                        stopStatusTracking();
                        resolve(data);
                    }
                })
                .catch(() => {
                    nextCheck = setTimeout(check, STATUS_TRACKING_PERIOD);
                });
        };

        check();
    });
}

function stopStatusTracking() {
    clearTimeout(nextCheck);
    statusTracking = null;
}

function getStatus(restoreId) {
    const data = {};

    return restoreApi.getCheckStatus(restoreId)
        .then(response => {
            _.merge(data, response.restore);
        })
        .catch(error => {
            data.current_check = error.response;
        })

        .then(() => restoreApi.getOwnershipStatus(restoreId))
        .then(response => {
            _.merge(data, response.restore);
        })
        .catch(error => {
            data.ownership = error.response;
        })

        .then(() => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, { restore: data });

            return data;
        });
}

function checkOwnership(restoreId, data) {
    return restoreApi.checkOwnership(restoreId, data)
        .then(response => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            return response.restore;
        })
        .catch(error => error.response);
}

function start(data) {
    return restoreApi.start(data)
        .then(response => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            return response.restore || response;
        })
        .catch(error => error.response);
}
