import { createBookmarks, removeBookmarks } from "./bookmark.js";
import { saveRevision, getRevision } from "./revision.js";


const saveBookmarks = async (id, bookmark) => {
  console.log('Saving bookmarks! id: ' + id + ' bookmark: ' + JSON.stringify(bookmark));
  await saveRevision();
}

const loadBookmarks = async () => {
  const data = await getRevision();
  if (!data)
    return;

  const savedRev = await chrome.storage.sync.get('revId');
  if (data.revId === savedRev.revId) {
    console.log('Same revision ID, no update required');
    return;
  }

  console.log('Different revision IDs found! Old: ' + data.revId + ' New:' + savedRev.revId);

  removeListeners();

  await chrome.storage.sync.set({ revId: data.revId });

  // TODO GD: "Raw" replacement, make this more efficient to avoid flickering
  for (var child of data.bookmarks[0].children) {
    await removeBookmarks(child.id);
    await createBookmarks(child.children, child.id);
  }

  addListeners();
}

function removeListeners() {
  console.log('Removing listeners!');
  chrome.bookmarks.onCreated.removeListener(saveBookmarks);
  chrome.bookmarks.onRemoved.removeListener(saveBookmarks);
  chrome.bookmarks.onChanged.removeListener(saveBookmarks);
  chrome.bookmarks.onMoved.removeListener(saveBookmarks);
  chrome.bookmarks.onChildrenReordered.removeListener(saveBookmarks);
}

function addListeners() {
  console.log('Adding listeners!');
  chrome.bookmarks.onCreated.addListener(saveBookmarks);
  chrome.bookmarks.onRemoved.addListener(saveBookmarks);
  chrome.bookmarks.onChanged.addListener(saveBookmarks);
  chrome.bookmarks.onMoved.addListener(saveBookmarks);
  chrome.bookmarks.onChildrenReordered.addListener(saveBookmarks);
}

addListeners();

loadBookmarks();

// TODO GD: Make this websocket based
setInterval(loadBookmarks, 10000);