// ==UserScript==
// @name           IITC plugin: Bannergress credentials backup/restore
// @author         DanielOnDiordna
// @category       Misc
// @version        2.0.0.20240212.202900
// @updateURL      https://softspot.nl/ingress/plugins/iitc-plugin-bannegresscredentialsbackuprestore.meta.js
// @downloadURL    https://softspot.nl/ingress/plugins/iitc-plugin-bannegresscredentialsbackuprestore.user.js
// @description    [danielondiordna-2.0.0.20240212.202900] Use the dialog of this plugin to create a backup of your Bannergress plugin credentials on a desktop and restore them in IITC-CE mobile. Step by step instructions are included.
// @id             iitc-plugin-bannegresscredentialsbackuprestore@danielondiordna
// @namespace      https://softspot.nl/ingress/
// @match          https://intel.ingress.com/*
// @grant          none
// ==/UserScript==

function wrapper(plugin_info) {
    // ensure plugin framework is there, even if iitc is not yet loaded
    if(typeof window.plugin !== 'function') window.plugin = function() {};

    // use own namespace for plugin
    window.plugin.bannegresscredentialsbackuprestore = function() {};
    let self = window.plugin.bannegresscredentialsbackuprestore;
    self.id = 'bannegresscredentialsbackuprestore';
    self.title = 'Bannergress credentials backup/restore';
    self.pluginname = 'plugin-' + self.id;
    self.version = '2.0.0.20240212.202900';
    self.author = 'DanielOnDiordna';
    self.changelog = `
Changelog:

version 2.0.0.20240212.202900
- completely updated version

version 1.0.0.20211006.160900
- first release
`;

    self.instructions = function() {
        let container = document.createElement('div');
        container.innerHTML = `
<p>The IITC Bannergress plugin requires you to log in, to be able to upload/sync/renew missions to the Bannergress servers.<br>
At this moment it is not (yet) possible to login on Bannergress for IITC mobile users.</p>

<p>This plugin offers a workaround for mobile usage of the IITC <a href="https://bannergress.com/">Bannergress plugin</a>:<br>
You can backup your Bannergress login credentials from a desktop, and you can restore these credentials on a mobile device.</p>

<p>Follow these steps to get logged into the Bannergress plugin on your mobile device:</p>

<h3>Backup</h3>

<ol>
<li>Run IITC on a desktop browser: use Chrome with <a href="https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo" target="_blank">Tampermonkey</a>, install the <a href="https://iitc.app/download_desktop" target="_blank">IITC-CE desktop release version</a>, the <a href="https://iitc.app/download_desktop#missions-by-jonatkins">Missions plugin</a> and the <a href="https://bannergress.com/help" target="_blank">Bannergress plugin</a> (see Part 1: setup).</li>
<li>Also install this <a href="https://softspot.nl/ingress/plugindetails/iitc-plugin-bannegresscredentialsbackuprestore" target="_blank">${self.title}</a> in Tampermonkey.</li>
<li>Open IITC on the desktop and press Login on the Bannergress plugin dialog. Make sure it says Authenticated.</li>
<li>Open the backup/restore dialog (from the toolbox menu or the Bannergress dialog), and create a backup of your Bannergress credentials.</li>
<li>Copy the credentials to your mobile device. You could use your Telegram Saved Messages chat. Be carefull: do not share your Bannergress credentials with other people!</li>
</ol>

<h3>Restore</h3>

<ol>
<li>Run IITC on your mobile device <a href="https://iitc.app/download_mobile.html" target="_blank">IITC mobile</a> and install the same Bannergress plugin.</li>
<li>Also install this <a href="https://softspot.nl/ingress/plugindetails/iitc-plugin-bannegresscredentialsbackuprestore" target="_blank">${self.title}</a> in IITC mobile.</li>
<li>Enable the plugins under Misc and the official Missions plugin under Info in IITC mobile.</li>
<li>Open IITC mobile and ignore the Bannergress plugin dialog, do not try to login.</li>
<li>Open the backup/restore dialog (from the toolbox menu or the Bannergress dialog), and restore your Bannergress credentials.</li>
<li>Reload IITC mobile and now the Bannergress plugin should be logged in. It should say Authenticated.</li>
</ol>

<p>Be aware that your backed up credentials may not stay valid over a longer period of time.<br>
You may need to repeat the backup and restore actions.</p>

<p>Be carefull: Do not share your Bannergress credentials backup with other people!</p>

<p class="${self.id}author">${self.title} version ${self.version} by ${self.author}</p>
`;
        window.dialog({
            html: container,
            id: self.pluginname + '-dialog',
            width: 'auto',
            title: self.title + ' - Instructions'
        }).dialog('option', 'buttons', {
            '< Main menu': self.menu,
            'Changelog': function() { alert(self.changelog); },
            'Close': function() { $(this).dialog('close'); }
        });
    };

    self.monitorBannergressDialog = function() {
        // ugly solution to keep checking for the bannergress dialog to show up to add an extra button:
        if (!document.querySelector('.bannerIndexer-settings-dialog-provider-area')) return;
        let menubutton = document.querySelector(`[name=${self.pluginname}menubutton]`);
        if (menubutton) {
            if (menubutton.nextElementSibling) {
                menubutton.parentNode.appendChild(menubutton); // move to the end
            }
            return;
        }
        menubutton = document.querySelector('.bannerIndexer-settings-dialog-provider-area').appendChild(document.createElement('button'));
        menubutton.name = `${self.pluginname}menubutton`;
        menubutton.style.marginLeft = '5px';
        menubutton.textContent = "Backup/restore...";
        menubutton.title = "Open the Bannergress credentials backup/restore menu";
        menubutton.addEventListener('click',function() {
            self.menu();
        },false);
    };

    self.menu = function() {
        let container = document.createElement('div');
        container.innerHTML = `
<h2>1. Backup</h2>
<p>These are your Bannergress credentials:</p>
<textarea name="backupdata" rows="6" cols="42" readonly></textarea>
<p><input type="button" name="backup" value="Backup (copy)"></p>

<h2>2. Restore</h2>
<p>Paste your Bannergress credentials data here to restore:</p>
<textarea name="restoredata" rows="6" cols="42"></textarea>
<p><input type="button" name="restore" value="Restore"></p>

<p>A reload of IITC is required after restore</p>
`;

        container.querySelector('textarea[name=backupdata]').value = localStorage["plugin.bannerIndexer.settings.bannergress"] || '';
        container.querySelector('input[name=backup]').addEventListener('click',function() {
            let textarea = container.querySelector('textarea[name=backupdata]');
            let success = false;
            try {
                // test this data
                let data = JSON.parse(textarea.value);
                success = (data.subject && data.token && data.refreshToken); // check for required keys
            } catch(e) {
            }
            if (success) {
                textarea.focus();
                textarea.select();
                document.execCommand("Copy");
                alert("Your Bannergress credentials are now copied to the clipboard.\n\nPaste the data in a file or private chat to transfer your backup anywhere.");
            } else {
                alert("Warning: There are no valid Bannergress credentials. There is nothing to backup.");
            }
        },false);

        container.querySelector('input[name=restore]').addEventListener('click',function() {
            let textarea = container.querySelector('textarea[name=restoredata]');
            textarea.value = textarea.value.replace(/^\s+|\s+$/g, ''); // trim spaces and newlines
            let success = false;
            try {
                // test this data
                let data = JSON.parse(textarea.value);
                success = (data.subject && data.token && data.refreshToken); // check for required keys
            } catch(e) {
            }

            if (success) {
                if (confirm("The data seems like valid Bannergress credentials.\n\nAre you sure you want to use this data as your Bannergress credentials?")) {
                    localStorage["plugin.bannerIndexer.settings.bannergress"] = textarea.value;
                    alert("Your Bannergress credentials are restored.\n\nReload IITC and check if the Bannergress plugin works with these credentials.");
                }
            } else {
                alert("Warning: These are no valid Bannergress credentials. There is nothing to restore.");
            }
        },false);

        window.dialog({
            html: container,
            id: self.pluginname + '-dialog',
            title: self.title,
            width: 'auto'
        }).dialog('option', 'buttons', {
            'Instructions': function() { self.instructions(); },
            'Ok': function() { $(this).dialog('close'); }
        });
    };

    self.setup = function() {
        if ('pluginloaded' in self) {
            console.log('IITC plugin already loaded: ' + self.title + ' version ' + self.version);
            return;
        } else {
            self.pluginloaded = true;
        }

        setInterval(self.monitorBannergressDialog,100); // ugly solution, would be better with MutationObserver

        var stylesheet = document.body.appendChild(document.createElement('style'));
        stylesheet.innerHTML = `
.${self.id}author {
    margin-top: 14px;
    font-style: italic;
    font-size: smaller;
}
`;

        let toolboxlink = document.getElementById('toolbox').appendChild(document.createElement('a'));
        toolboxlink.textContent = self.title;
        toolboxlink.addEventListener('click', function(e) {
            e.preventDefault();
            self.menu();
        }, false);

        console.log('IITC plugin loaded: ' + self.title + ' version ' + self.version);
    };

    var setup = function() {
        (window.iitcLoaded?self.setup():window.addHook('iitcLoaded',self.setup));
    };

    setup.info = plugin_info; //add the script info data to the function as a property
    if(!window.bootPlugins) window.bootPlugins = [];
    window.bootPlugins.push(setup);
    // if IITC has already booted, immediately run the 'setup' function
    if(window.iitcLoaded && typeof setup === 'function') setup();
} // wrapper end
// inject code into site context
var script = document.createElement('script');
var info = {};
if (typeof GM_info !== 'undefined' && GM_info && GM_info.script) info.script = { version: GM_info.script.version, name: GM_info.script.name, description: GM_info.script.description };
script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');'));
(document.body || document.head || document.documentElement).appendChild(script);