export class Queue<T> {
  private items: T[] = [];
  private storageKey = "notiQueue";

  private constructor(items: T[]) {
    this.items = items;

    // Lắng nghe thay đổi từ tab khác
    chrome.storage.onChanged.addListener((changes, areaName) => {
      if (areaName === "local" && changes[this.storageKey]) {
        this.items = changes[this.storageKey].newValue
          ? JSON.parse(changes[this.storageKey].newValue)
          : [];
        console.log("Queue updated from another tab:", this.items);
      }
    });
  }

  static async create<T>(): Promise<Queue<T>> {
    const storageKey = "notiQueue";
    const res = await chrome.storage.local.get(storageKey);
    const items = res[storageKey] ? JSON.parse(res[storageKey]) : [];
    return new Queue<T>(items);
  }

  private async save() {
    await chrome.storage.local.set({
      [this.storageKey]: JSON.stringify(this.items),
    });
  }

  async enqueue(item: T) {
    this.items.push(item);
    await this.save();
  }

  async dequeue(): Promise<T | undefined> {
    const item = this.items.shift();
    await this.save();
    return item;
  }

  peek(): T | undefined {
    return this.items[0];
  }

  isEmpty(): boolean {
    return this.items.length === 0;
  }

  size(): number {
    return this.items.length;
  }
}
