import { fetchDomains, switchDomain, currentDomain } from '../services/domain';
import { getDomain, setDomain } from '../utils/auth';

export default {

  namespace: 'domain',

  state: {
    init: undefined,
    list: [],
  },

  subscriptions: {
    setup({ dispatch }) {  // eslint-disable-line
    },
  },

  effects: {
    *fetch(ignored, { put, call }) {
      const domain = yield call(getDomain);
      const init = domain ? domain.path : undefined;
      const list = yield call(fetchDomains, '/', true);
      yield put({ type: 'queryInit', payload: init });
      yield put({ type: 'queryList', payload: list });
    },
    *switch({ payload: domainPath }, { put, call }) {
      yield call(switchDomain, domainPath);
      const { path, name } = yield call(currentDomain);
      yield call(setDomain, name, path);
      yield put({ type: 'queryInit', payload: path });
    },
  },

  reducers: {
    queryInit(state, { payload: init }) {
      return {
        ...state,
        init,
      };
    },
    queryList(state, { payload: list }) {
      return {
        ...state,
        list,
      };
    },
  },

};
