import {
  emitter,
  EVENT_HISTORY_GO,
  EVENT_HISTORY_BACK,
  EVENT_HISTORY_CHANGE
} from '@vtj/engine';

export class History {
  index: number = 0;
  list: string[] = [];
  max: number;
  constructor(list: string[], max: number = 30) {
    this.max = max;
    this.refresh(list);
  }

  refresh(list: string[]) {
    this.index = 0;
    this.list = list;
  }

  go() {
    const { index, list } = this;
    if (index <= 0) return;
    --this.index;
    const item = list[this.index];
    emitter.emit(EVENT_HISTORY_GO, item);
    emitter.emit(EVENT_HISTORY_CHANGE, item);
  }

  back() {
    const { index, list } = this;
    if (index >= list.length - 1) return;
    ++this.index;
    const item = list[this.index];
    emitter.emit(EVENT_HISTORY_BACK, item);
    emitter.emit(EVENT_HISTORY_CHANGE, item);
  }

  push(item: string) {
    const { max, list } = this;
    list.unshift(item);
    if (list.length > max) {
      this.list = list.splice(max);
    }
    this.index = 0;
  }

  load(item: string) {
    const index = this.list.findIndex((n) => n === item);
    if (index >= 0) {
      this.index = index;
      emitter.emit(EVENT_HISTORY_CHANGE, item);
    }
  }
}
