class UndoRedo {
	constructor() {
		this.undo_stack = [];
		this.redo_stack = [];

		//撤销、重做的状态
		this.can_undo = false;
		this.can_redo = false;

		//唯一标识插入的数据
		this.count = 0;
	}

	//撤销
	undo = () => {
		const item = this.undo_stack.pop();
		this.redo_stack.push(item);
		this.statusControl();
		return this.last();
	}

	//重做
	redo = () => {
		const item = this.redo_stack.pop();
		this.undo_stack.push(item);
		this.statusControl();
		return item;
	}

	//插入数据
	insert = (data) => {
		//缓存undo_stack
		const undo_stack = this.undo_stack;
		//使用属性key来标识数据
		const obj = {
			key: this.count,
			...data
		};

		//新插入的数据是否和前一条数据连续
		if (undo_stack.length > 0 && !this.isDataSeries(obj.key)) {
			this.redo_stack = [];
		}

		undo_stack.push(obj);

		this.statusControl();

		this.count++;
	}

	//undo_stack栈顶元素
	last = () => {
		const undo_stack = this.undo_stack;
		return undo_stack[undo_stack.length - 1];
	}

	//数据是否连续
	isDataSeries = (key) => {
		const last_key = this.last().key;
		return (last_key + 1) === key
	}

	//状态控制
	statusControl = () => {
		this.can_undo = (this.undo_stack.length > 1);
		this.can_redo = (this.redo_stack.length > 0);
	}


}

export {
	UndoRedo
}