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

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

//TODO calculate period
const FORMAT = "YYYY-MM-DD"; //ISO date format

let { params = {} } = global.cfg;

const initialState = {
	status: "success",
	params: {
		dateType: params.dateType || "BILLED_DATE",
		aggregate: true,
		aggregatedAmount: 10000,
		from: moment().startOf("month").subtract("month", 2).format(FORMAT),
		to: moment().endOf("month").format(FORMAT)
	},
	options: {
		status: "pending",
		tax: []
	},
	data: {},
	empty: true
};

let reducer = createReducer(initialState);

export function taxReportOptionsAction(unitId, params) {
	return {
		type: '@@taxReport/FETCH_OPTIONS',
		payload: backendRequest(`/api/${unitId}/reports/tax/types`, "GET", { params }),
		meta: {
			unitId: unitId,
			params
		}
	}
}

reducer.handleAction("@@taxReport/FETCH_OPTIONS_PENDING", (state, action) => state.set("options", fromJS({ status: "pending" })));
reducer.handleAction("@@taxReport/FETCH_OPTIONS_FULFILLED", (state, action) => {
	let data = action.payload.body;
	return state.setIn(["options", "status"], "success").setIn(["options", "tax"], fromJS(data));
});
reducer.handleAction("@@taxReport/FETCH_OPTIONS_REJECTED", (state, action) => state.setIn(["options", "status"], "failure").setIn(["options", "tax"], []));


export function taxReportAction(unitId, params) {
	return {
		type: '@@taxReport/FETCH',
		payload: backendRequest(`/api/${unitId}/reports/tax`, "GET", { params }),
		meta: {
			unitId: unitId,
			params
		}
	}
}

reducer.handleAction("@@taxReport/FETCH_PENDING", (state, action) => state.set("status", "pending").set("params", action.meta.params));
reducer.handleAction("@@taxReport/FETCH_FULFILLED", (state, action) => {
	let { params, ...data } = action.payload.body;
	return state.set("status", "success").set("params", fromJS(params)).set("data", fromJS(data));
});
reducer.handleAction("@@taxReport/FETCH_REJECTED", (state, action) => state.set("status", "failure").delete("data") );


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

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