import findIndex from 'lodash/array/findIndex'
import clone from 'lodash/lang/clone'
import reject from 'lodash/collection/reject'

import {
	LOG_MESSAGE,
	LOG_ERROR,
	START_PROGRESS,
	INCREMENT_PROGRESS,
	REMOVE_NOTIFICATION,
} from '../constants/notifications'

const initialState = []

export default function reducer(state = initialState, action) {
	const {type, payload} = action

	if (payload && type !== REMOVE_NOTIFICATION && findIndex(state, {id: payload.id}) >= 0) {
		console.error(`cannot add a second notification with an existing id "${payload.id}"`)
		return state
	}

	switch (type) {
		case LOG_MESSAGE: {
			return [...state, {
				id: payload.id,
				message: payload.message,
				type: 'message',
			}]
		}

		case LOG_ERROR: {
			return [...state, {
				id: payload.id,
				message: payload.error.message,
				type: 'error',
			}]
		}

		case START_PROGRESS: {
			return [...state, {
				id: payload.id,
				message: payload.message,
				value: payload.value,
				max: payload.max,
				showButton: payload.showButton,
				type: 'progress',
			}]
		}

		case INCREMENT_PROGRESS: {
			// make a copy of the previous item
			const itemIndex = findIndex(state, {id: payload.id})
			const progress = clone(state[itemIndex])
			progress.value += payload.by
			progress.value = progress.value <= progress.max
				? progress.value
				: progress.max

			return [
				...state.slice(0, itemIndex),
				progress,
				...state.slice(itemIndex + 1),
			]
		}

		case REMOVE_NOTIFICATION: {
			return reject(state, {id: payload.id})
		}

		default: {
			return state
		}
	}
}

@@ -286,341 +286,432 @@
 %5B%5D%0A%0A
-export default function reducer(state = initialState, action) %7B%0A%09const %7Btype, payload%7D = action%0A%0A%09if (payload && type !== REMOVE_NOTIFICATION && findIndex(state, %7Bid: payload.id%7D) %3E= 0) %7B%0A%09%09console.error(%60cannot add a second notification with an existing id %22$%7Bpayload.id%7D%22%60)%0A%09%09return state%0A%09%7D%0A%0A%09switch (type) %7B%0A%09%09case LOG_MESSAGE: %7B
+function checkForDuplicateIds(state, %7Bpayload%7D) %7B%0A%09if (findIndex(state, %7Bid: payload.id%7D) %3E= 0) %7B%0A%09%09console.error(%60cannot add a second notification with an existing id %22$%7Bpayload.id%7D%22%60)%0A%09%09return true%0A%09%7D%0A%09return false%0A%7D%0A%0Aexport default function reducer(state = initialState, action) %7B%0A%09const %7Btype, payload%7D = action%0A%0A%09switch (type) %7B%0A%09%09case LOG_MESSAGE: %7B%0A%09%09%09if (checkForDuplicateIds(state, action)) %7B%0A%09%09%09%09return state%0A%09%09%09%7D%0A
 %0A%09%09%09
@@ -828,24 +828,93 @@
 OG_ERROR: %7B%0A
+%09%09%09if (checkForDuplicateIds(state, action)) %7B%0A%09%09%09%09return state%0A%09%09%09%7D%0A%0A
 %09%09%09return %5B.
@@ -1031,24 +1031,93 @@
 PROGRESS: %7B%0A
+%09%09%09if (checkForDuplicateIds(state, action)) %7B%0A%09%09%09%09return state%0A%09%09%09%7D%0A%0A
 %09%09%09return %5B.

put the id check into the cases where it's needed