import _ from "lodash";
import { IPC_TAGUPDATE } from "../actions/actions_tags";
import {history_tags as historyTags} from "../../../tagList.json";
import { IPC_TAGHISTORYUPDATE } from "../actions/actions_taghistory";

const historyPoints = 50000;


export default function(state = {}, action){
	switch (action.type) {
	case IPC_TAGUPDATE:
		const { tagName, value } = action.payload;
		if (historyTags.includes(tagName)){
			const thisEntry = {
				value,
				timestamp: new Date()
			};
			let tagHistory = [ thisEntry ]; 
			if (state[tagName]){
				tagHistory = _.take(_.concat(tagHistory, state[tagName]), historyPoints);
			}
			return { ...state, [tagName]: tagHistory};

		} else {
			return state;
		}

	case IPC_TAGHISTORYUPDATE:
		const { tagName: name, historyRows } = action.payload;
		const thisTagHistory = _.map(historyRows, ({value, timestamp}) => {
			return {
				value,
				timestamp: new Date(timestamp)
			};
		});
		return { ...state, [name]: thisTagHistory};


	default:
		return state;
	}
}