// ==UserScript==
// @include        https://read.amazon.com/*
// @require        utils.js
// ==/UserScript==

// This placeholder gets munged with real data at build time.
var WebappsGettextDict = JSON.parse(unescape(
    "%7B%22GETTEXT%22%3A%22PLACEHOLDER%22%7D"
));

window.Unity = external.getUnityObject(1);

function getBookList() {
    var res = [];
    try {
        var doc = document.getElementById('KindleLibraryIFrame').contentDocument;
        var books = doc.getElementById('titles_inner_wrapper').children;
        var i;

        for (i = 0; i < books.length; i++) {
            var title = doc.evaluate('div/img', books[i], null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue.title;
            var link = 'https://read.amazon.com/?asin=' + books[i].id;
            var count = books.length - i;

            res.push({ name: title,
                       url: link,
                       count: count });
        }
        localStorage.setItem(FAVORITES, JSON.stringify(res));
        return res;
    } catch (x) {
        if (localStorage.getItem(FAVORITES)) {
            res = JSON.parse(localStorage.getItem(FAVORITES));
        }
    }

    return res;
}

function unityLoaded() {
    var count = 3;
    setTimeout(function self() {
        var list = getBookList();
        if (!list.length && count < 0) {
            list = JSON.parse(localStorage.getItem(FAVORITES));
            if (!list) {
                list = [];
            }
        }
        if (list.length) {
            addFavoritesInLauncher(list);
            return;
        }
        setTimeout(self, 6000);
        count--;
    }, 2000);
}

Unity.init({ name: _('Amazon Cloud Reader'),
             domain: 'read.amazon.com',
             homepage: 'https://read.amazon.com/',
             iconUrl: 'icon://amazon-store',
             onInit: wrapCallback(unityLoaded) });
