import createReducer from 'lib/reducer';
import backendRequest from 'lib/backend';
import { settingsSelector } from 'utils/settings';

import { fromJS } from "immutable";
import moment from 'moment';


const initialState = {
	status: "pending",
	params: {
		aggregate: true,
		aggregatedAmount: 10000
	},
	data: {}
};

let reducer = createReducer(initialState);

export function fetchSettingsAction(unitId) {
	return {
		type: '@@dphReport/FETCH_SETTINGS',
		payload: backendRequest(`/api/${unitId}/dph`, "GET"),
		meta: {
			unitId: unitId
		}
	}
}

export function saveSettingsAction(unitId, settings) {
	return {
		type: '@@dphReport/SAVE_SETTINGS',
		payload: backendRequest(`/api/${unitId}/dph`, "PUT", { body: settings }),
		meta: {
			unitId: unitId,
			settings
		}
	}
}


reducer.handleAction("@@dphReport/FETCH_SETTINGS_PENDING", (state, action) => state.set("isSettingsPending", true));
reducer.handleAction("@@dphReport/FETCH_SETTINGS_FULFILLED", (state, action) => {
	let settings = action.payload.body;
	return state.set("isSettingsPending", false).set("settings", fromJS(settings)).set("defaultParams", prepareDefaultSettings(settings));
});
reducer.handleAction("@@dphReport/FETCH_SETTINGS_REJECTED", (state, action) => state.set("isSettingsPending", false) );


reducer.handleAction("@@dphReport/SAVE_SETTINGS_PENDING", (state, action) => state.set("isSettingsPending", true));
reducer.handleAction("@@dphReport/SAVE_SETTINGS_FULFILLED", (state, action) => {
	let settings = action.payload.body;
	return state.set("isSettingsPending", false).set("settings", fromJS(settings)).set("defaultParams", prepareDefaultSettings(settings));;
});
reducer.handleAction("@@dphReport/SAVE_SETTINGS_REJECTED", (state, action) => state.set("isSettingsPending", false).delete("settings") );


export const selector = settingsSelector((state) => {
	return state.get("dphReport").toJS();
});

//export reducer
export default reducer.export();


function prepareDefaultSettings(settings) {
	let 
		params = {},
		m = moment();

	params.date = m.format("YYYY-MM-DD");

	if (settings.periodType = "QUARTER") {
		m = m.subtract(1, "quarter");
		params.year = m.year();
		params.quarter = m.quarter();
	} else {
		m = m.subtract(1, "month");
		params.year = m.year();
		params.month = m.month();
	}

	return fromJS(params);
}