import _ from 'lodash';
import Immutable from 'immutable';
import { ReduceStore } from 'flux/utils';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import Dkim from 'records/Dkim';

const TERMINAL_STATUSES = ['failed', 'success'];

class MailStore extends ReduceStore {
    getInitialState() {
        return Immutable.fromJS({
            settings: {},
            dkim: {},
        });
    }

    reduce(state, action) {
        const { data, type } = action;

        switch (type) {
            case ActionTypes.RECEIVE_MIXED_DATA:
                return this._receiveMixedData(data, state);
        }

        return state;
    }

    _receiveMixedData(data, state) {
        if (data.mail_import) {
            state = state.set('import', Immutable.fromJS(data.mail_import));
        }

        if (data.mail_settings) {
            state = state.set('settings', Immutable.fromJS(data.mail_settings));
        }

        if (data.dkim) {
            state = state.set('dkim', new Immutable.Map(data.dkim).map(Dkim.create));
        }

        return state;
    }

    getDkimList() {
        return this._state.get('dkim').toArray();
    }

    getDkim(domain) {
        return this._state.getIn(['dkim', domain]);
    }

    getSettings() {
        return this._state.get('settings');
    }

    getImportProgress() {
        const progress = this._state.getIn(['import', 'progress']);

        return progress ? progress.toJS() : [];
    }

    getImportStatus() {
        const status = this._state.getIn(['import', 'status']);

        if (status) {
            return status;
        }

        const progress = this.getImportProgress();

        if (!progress.length) {
            return;
        }

        const statusCount = {};

        progress.forEach(item => {
            if (item && item.state) {
                const key = _.snakeCase(item.state);

                statusCount[key] = (statusCount[key] || 0) + 1;
            }
        });

        if (statusCount.failed) {
            return 'failed';
        }

        if (statusCount.in_progress || statusCount.pending) {
            return 'in_progress';
        }

        return 'success';
    }

    isImportComplete() {
        return TERMINAL_STATUSES.indexOf(this.getImportStatus()) !== -1;
    }

    getImportStage() {
        const progress = this.getImportProgress();
        let stage;

        for (let i = 0; i < progress.length && !stage; i++) {
            if (TERMINAL_STATUSES.indexOf(progress[i].state) === -1) {
                stage = progress[i].stage;
            }
        }

        return stage;
    }
}

export default window.ya.connect.MailStore = new MailStore(dispatcher);
