import Immutable from 'immutable';
import * as types from '../constants/actionTypes';
import NoteRecord from '../store/noteRecord';
const findNoteIndex = (notes, id) => {
return notes.findIndex((note) => note.get('_id') === id);
}
const findNote = (notes, id) => {
return notes.get(findNoteIndex(notes, id));
}
export default (state = Immutable.List([]), action) => {
switch (action.type) {
case types.ADD_NOTE: {
return state.push(new NoteRecord(action.note));
}
case types.DELETE_NOTE: {
const noteIndex = findNoteIndex(state, action.note.get('_id'));
const note = findNote(state, action.note.get('_id'));
return state.set(noteIndex, note.merge({deleted:true, modified:true}));
}
case types.DO_DELETE_NOTE: {
const noteIndex = state.findIndex((note) => note.get('_id') === action.note.get('_id'));
return state.delete(noteIndex);
}
case types.UPDATE_NOTE: {
const index = findNoteIndex(state, action.note.get('_id'));
const note = findNote(state, action.note.get('_id'));
let newNote = note.merge(action.data, {modified:true});
return state.set(index, newNote);
}
case types.DELETE_SESSION: {
const sessionId = action.session.get('_id');
return state.map((note) => {
if(sessionId === note.session) {
return note.merge({deleted:true, modified:true});
} else {
return note;
}
})
}
default:
return state;
}
};