import createReducer, { safe } from 'lib/reducer';
import backendRequest from 'lib/backend';
import reduxList from 'lib/redux-list';
import { listRequest, listResponse } from 'lib/list-backend';
import { settingsSelector } from 'utils/settings';


import { fromJS, toJS } from 'immutable';

import moment from 'moment';


let initialState = {
	periodParams: {
		periodType: 'last12Months'
	},
	list: {
		status: 'pending',
		fresh: true,
		paging: {
			pageSize: 15
		},
		data: []
	},

	stats: {
		status: 'pending',
		data: {
			total: 0,
			values: {
			}
		}
	},
};

let reducer = createReducer(initialState);


let api = reduxList("home/dashboard", {
	reducer, 
	fetchRequest: listRequest(() => `/api/ratings`),
	fetchResponse: listResponse()
}); 

//export actions
export const fetchRatingsAction = api.actions.fetchList;

//TODO
export const selector = settingsSelector((state, props) => {
	let home = safe(state.get("home"));
	let list = api.selector(state, props);
	return home;
});




export function fetchStatsAction(unitId, from, to, dateType) {
	return {
		type: 'home/FETCH_STATS',
		payload: backendRequest('/api/ratings/stats', 'GET', { params: { from, to } })
	};
};

reducer.handleAction('home/FETCH_STATS_PENDING', (state, action) => 
	state.setIn(["stats", "status"], "pending")
);
reducer.handleAction('home/FETCH_STATS_FULFILLED', (state, action) => 
	state
		.setIn(["stats", "status"], "success")
		.setIn(["stats", "data"], action.payload.body)
		.deleteIn(["stats", "error"])
);
reducer.handleAction('home/FETCH_STATS_REJECTED', (state, action) => 
	state.setIn(["stats", "status"], "failed").deleteIn(["stats", "data"]).setIn(["stats", "error"], true)
);




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

