import { call, put, select } from 'redux-saga/effects';
import { SubmissionError } from 'redux-form';
import * as types from '~/store/actionTypes';
import { Nixplay } from '~/lib/sdk';
import { resolveCallback, rejectCallback } from './helper';

import * as selectors from './selectors';


export function* getSettings() {
	try {
		const token = yield select(selectors.token);
		const settings = yield call(Nixplay.settings.getSettings, token);
		yield put({ type: types.GET_SETTINGS_SUCCESS, payload: { settings } });
	} catch (error) {
		yield put({ type: types.GET_SETTINGS_ERROR, payload: { error } });
	}
}

export function* setSettings(action) {
	try {
		const token = yield select(selectors.token);
		yield call(Nixplay.settings.setSettings, token, action.payload.settings);
		yield put({ type: types.SET_SETTINGS_SUCCESS, payload: { settings: action.payload.settings } });
		yield call(resolveCallback, action);
	} catch (error) {
		yield put({ type: types.SET_SETTINGS_ERROR, payload: { error } });
		yield call(rejectCallback, new SubmissionError({ _error: error }));
	}
}

export function* changeUserSettings(action) {
	try {
		const token = yield select(selectors.token);
		yield call(
			Nixplay.settings.changeUserSettings,
			token,
			action.payload,
		);
		yield put({
			type: types.SUBMIT_CHANGE_USER_SETTINGS_SUCCESS,
			payload: action.payload,
		});
		yield put({ type: types.GET_USER_PROFILE });
		yield call(resolveCallback, action);
	} catch (error) {
		yield put({ type: types.SUBMIT_CHANGE_USER_SETTINGS_FAIL, payload: { error } });
		yield call(action.payload.reject, new SubmissionError({ error }));
	}
}
