/**
 * @file    signal-store.js
 * @brief   信号数据缓存 — 接收 WS 推送并更新内存 + localStorage 持久化
 */


var SignalStore = {
	data: { out: [], in: [], yk: [], ao: [], param: [] },

	/**
	 * @brief 合并 WS 推送数据到缓存, 并持久化到 localStorage
	 * @param {object} push  {out:[...], in:[...], ...}
	 */
	update: function(push) {
		var self = this;
		['out', 'in', 'yk', 'ao', 'param'].forEach(function(type) {
			if (push[type])
			{
				var map = {};
				self.data[type].forEach(function(s) { map[s.saddr] = s; });
				push[type].forEach(function(s) { map[s.saddr] = s; });
				self.data[type] = Object.keys(map).map(function(k) { return map[k]; });
			}
		});
		this._save();
	},

	get: function(type) {
		return this.data[type] || [];
	},

	addFromPush: function(type, item) {
		this.data[type].push(item);
		this._save();
	},

	remove: function(type, saddr) {
		this.data[type] = this.data[type].filter(function(s) { return s.saddr !== saddr; });
		this._save();
	},

	/** @brief 从 localStorage 恢复缓存 */
	restore: function() {
		try {
			var saved = localStorage.getItem('rtu_signals');
			if (saved) {
				var parsed = JSON.parse(saved);
				if (parsed && parsed.out) { this.data = parsed; }
			}
		} catch (e) { /* ignore corrupt data */ }
	},

	/** @brief 持久化到 localStorage (debounced) */
	_save: function() {
		var self = this;
		if (this._timer) clearTimeout(this._timer);
		this._timer = setTimeout(function() {
			try { localStorage.setItem('rtu_signals', JSON.stringify(self.data)); } catch (e) {}
		}, 500);
	}
};
