import { types } from "../actions/actionTypes";
import { readLocalStorage, writeLocalStorage } from "../utils/helperMethods";
import * as Config from "../utils/Config";

const initialLocalSettings = {
	serverType: Config.DEFAULT_SERVERTYPE,
  ricCodeSetting: Config.DEFAULT_RIC_CODE
};

const updateInitialLocalSettings = () => {
	const data = readLocalStorage('localSettings',initialLocalSettings);
	if( Object.keys(data).length !== Object.keys(initialLocalSettings).length){
		writeLocalStorage('localSettings', initialLocalSettings);
		return initialLocalSettings;
	}else{
		return data;
	}
};

export const localSettingsReducer = (state = updateInitialLocalSettings(), action) => {
  switch (action.type) {
    case types.CHANGE_LOCAL_SETTINGS: {
			const newState = Object.assign({}, state, action.payload);
			writeLocalStorage('localSettings', newState);
			return newState;
    }
    default:
      return state;
  }
};

export default localSettingsReducer;
