import _ from 'lodash';
import {
	GET_USER_ACTIVITIES,
	GET_USER_ACTIVITIES_SUCCESS,
	GET_USER_ACTIVITIES_ERROR,
	SET_SHOWN_MEDIA_STATUS,
	LOGOUT_SUCCESS,
} from '~/store/actionTypes';

export const initialState = {
	activities: [],
	isShown: false,
};

const processActivities = (state, payload) => {
	const activities = _.uniqBy([...payload.activities.activities, ...state.activities], 'timestamp');
	const sortedActivities = activities.sort((a, b) => b.timestamp - a.timestamp);
	if (sortedActivities.length > 0) {
		const [latestActivity] = sortedActivities;
		sortedActivities.activity = latestActivity;
	}
	return {
		...state,
		activities: sortedActivities,
		meta: { ...state.meta, loading: false, error: '' },
		isShown: false,
	};
};

export const userActivities = (state = initialState, { type, payload }) => {
	switch (type) {
		case GET_USER_ACTIVITIES:
			return { ...state, meta: { ...state.meta, loading: true, error: '' } };
		case GET_USER_ACTIVITIES_SUCCESS:
			return processActivities(state, payload);
		case GET_USER_ACTIVITIES_ERROR:
			return { ...state, meta: { ...state.meta, loading: false, error: payload.error } };
		case SET_SHOWN_MEDIA_STATUS:
			return { ...state, isShown: payload.isShown };
		case LOGOUT_SUCCESS:
			return initialState;
		default:
			return state;
	}
};
