export async function saveRevision() {
    const tree = await chrome.bookmarks.getTree();
    const apiUrl = await chrome.storage.sync.get('apiUrl');
    const syncToken = await chrome.storage.sync.get("syncToken");
    if (!apiUrl || !syncToken)
        return;


    const savedRev = await chrome.storage.sync.get('revId');

    const url = apiUrl.apiUrl + '/saveRevision';
    const options = {
        headers: {
            'content-type': 'application/json',
            'syncToken': syncToken.syncToken
        },
        method: 'POST',
        body: JSON.stringify({
            'revId': savedRev.revId,
            'bookmarks': tree
        })
    };

    try {
        const response = await fetch(url, options);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json(); // Convert to JSON
        await chrome.storage.sync.set({ revId: data.revId });

    } catch (e) {
        // TODO GD: Indicate error
    }
}

export async function getRevision() {
    const apiUrl = await chrome.storage.sync.get('apiUrl');
    const syncToken = await chrome.storage.sync.get("syncToken");

    if (!apiUrl || !syncToken)
        return;

    const url = apiUrl.apiUrl + '/getRevision';
    const options = {
        headers: {
            'content-type': 'application/json',
            'syncToken': syncToken.syncToken
        },
        method: 'GET'
    };

    try {
        const response = await fetch(url, options);
        if (!response.ok)
            throw new Error(`HTTP error! Status: ${response.status}`);

        return await response.json();
    } catch (e) {
        console.log(e);
        return null;
    }
}