<script type="text/javascript" src="{{ url_for('static', filename='hwi.js') }}"></script>

{# === pin screen ==== #}
{% include 'includes/hwi/components/pin.jinja' %}
{# === passphrase screen ==== #}
{% include 'includes/hwi/components/passphrase.jinja' %}
{# === device selector ==== #}
{% include 'includes/hwi/components/select_device.jinja' %}
{# === wallet specific stuff ==== #}
{% include 'includes/hwi/components/wallet.jinja' %}


<div id="hwi_progress" class="hidden" style="width: 270px;">
    <h1 id="hwi_progress_title">{{ _("Processing...") }}</h1>
    <div class="flex-center" id="hwi_progress_text">{{ _("Keep your wallet connected.") }}</div><br>
    <p id="bitbox02-pairing-code" style="margin: auto;"></p>
    <img src="{{ url_for('static', filename='img/loader_boxes.svg') }}">
    <div class="flex-center hidden" id="hwi_progress_note" style="cursor: pointer;">
        {{ _("If your device does not show up, ensure the Specter USB settings are correctly configured.") }}<br><br>
        <a href="{{ url_for('settings_endpoint.hwi') }}" style="color: #fff; text-decoration: underline; cursor: pointer;">
            {{ _("View USB settings") }}
        </a>
    </div>
    <br>
</div>

<div class="flex-column hidden" id="coldcard_warning">
    <p> {{ _("Do you really want to use your Coldcard over USB (no airgap)?") }} </p>
    <div class="flex-center">
        <button onclick="coldCardNotice()" class="btn flex-center"> {{ _("Yes, I am living on the edge!") }} </button>
    </div> <br>
    <div class="flex-center">
        <button onclick = "goToCoinkite()" class="btn flex-center"> {{ _("No, I'll use the address explorer on the Coldcard. Get me to the coinkite site for more info.") }} </button>
    </div>
</div>

<script type="text/javascript">
    let hwiURL = '/hwi/api/';
    if (
        '{{ specter.hwi_bridge_url }}'.startsWith('http://localhost') ||
        '{{ specter.hwi_bridge_url }}'.startsWith('http://127.0.0.1')
    ) {
        hwiURL = '{{ specter.hwi_bridge_url }}';
    }
    var hwi = new HWIBridge(hwiURL, '{{ specter.chain }}');
</script>

<script type="text/javascript">

    function showHWIProgress(title=`{{ _("Processing...") }}`, text=`{{ _("Keep your wallet connected.") }}`){
        document.getElementById('hwi_progress_title').innerHTML = title;
        document.getElementById('hwi_progress_text').innerHTML = text;
        showPageOverlay('hwi_progress');
    }

    function handleHWIError(error){
        console.error(error);
        if(error.message !== undefined){
            error = error.message;
        }
        showError(error, 10000);
        if(overlayIsActive()){
            hidePageOverlay();
        }
    }

    var coldcardUsb = 0;
    function coldCardNotice(){
        coldcardUsb = 1;
        cancelOverlay();
    }

    function goToCoinkite(){
        parent.open("https://blog.coinkite.com/address-explorer/");
        cancelOverlay();
    }

    async function enumerate(deviceTypes=null, devicePath=null, passphrase=''){
        // special handling of coldcard 
        if (deviceTypes == 'coldcard' && coldcardUsb == 0) {
             document.getElementById("page_overlay_popup_content").appendChild(document.getElementById("coldcard_warning"));
                }
        // detect device
        if (devicePath == null) {
            showHWIProgress(`{{ _("Detecting...") }}`, `{{ _("Plug in your device") }}`);
        }
        let result = [];
        let retryCounter = 0;
        try {
            try {
                result = await hwi.enumerate(passphrase, deviceTypes == 'bitbox02');
            } catch (e) {
                if (e.message !== 'Fetch is aborted' && e.message !== 'The user aborted a request.') {
                    throw e;
                }
                if (deviceTypes == 'bitbox02') {
                    // Likely bitbox02 pairing
                    let pairingCode = (await hwi.getBitbox02PairingCode()).code;
                    if (pairingCode) {
                        document.getElementById('bitbox02-pairing-code').innerHTML = `{{ _("Pairing Code") }}:<br><br><b>${pairingCode}</b><br><br>{{ _("Please confirm the code matches the one displayed on your BitBox02 device.<br><br>It could take up to 20 seconds to continue after approving the pairing on the device, please be patient.") }}`;
                    }
                }   
            }
            if(result!=null && deviceTypes!=null){
                result = result.filter(dev => deviceTypes.includes(dev.type));
            }
            if(result!=null && devicePath!=null){
                result = result.filter(dev => dev.path == devicePath);
            }
            while(result.length == 0){
                await wait(1000);
                // check that we still need to do it
                // just before the request
                if(!overlayIsActive()){
                    // showNotification("HWI is ready again", 10000);
                    return null;
                }
                console.log("Retrying enumerate...");
                try {
                    result = await hwi.enumerate(passphrase, deviceTypes == 'bitbox02');
                } catch (e) {
                    if (e.message !== 'Fetch is aborted' && e.message !== 'The user aborted a request.') {
                        throw e;
                    }
                    if (deviceTypes == 'bitbox02') {
                        // Likely bitbox02 pairing
                        let pairingCode = (await hwi.getBitbox02PairingCode()).code;
                        if (pairingCode) {
                            document.getElementById('bitbox02-pairing-code').innerHTML = `{{ _("Pairing Code") }}:<br><br><b>${pairingCode}</b><br><br>{{ _("Please confirm the code matches the one displayed on your BitBox02 device.<br><br>It could take up to 20 seconds to continue after approving the pairing on the device, please be patient.") }}`;
                        }
                    }   
                }
                if(result!=null && deviceTypes!=null){
                    result = result.filter(dev => deviceTypes.includes(dev.type));
                }
                if(result!=null && devicePath!=null){
                    result = result.filter(dev => dev.path == devicePath);
                }
                if (retryCounter > 5) {
                    document.getElementById('hwi_progress_note').style.display = 'block';
                }
                retryCounter++;
            }
        } catch (error) {
            handleHWIError(error);
            return null;
        }
        console.log(result);
        document.getElementById('bitbox02-pairing-code').innerHTML = "";
        if(!overlayIsActive() && devicePath == null){
            // showNotification("HWI is ready again", 10000);
            // no need to proceed at all
            return null;
        }
        if (devicePath == null){
            hidePageOverlay();
        }
        return result;
    }

    async function getXpubs(device, account=0, passphrase=""){
        // detect device
        showHWIProgress(`{{ _("Extracting public keys...") }}`, 
            `{{ _("It may take a while.") }}<br><br>{{ _("Keep your") }} ${capitalize(device.type)} {{ _("connected") }}.`);
        let result = [];
        try {
            result = await hwi.getXpubs(device, account, passphrase);
        } catch (error) {
            handleHWIError(error);
            return null;
        }
        if(!overlayIsActive()){
            // showNotification("HWI is ready again", 3000);
            // no need to proceed at all
            return null;
        }
        hidePageOverlay();
        return result;
    }

    async function getXpub(device, derivation="", passphrase="", chain=""){
        // detect device
        showHWIProgress(`{{ _("Extracting public key...") }}<br><span style=\'font-size: 0.8em;\'>{{ _("Derivation") }}: ` + derivation + "</span>", 
            `{{ _("It may take a while.") }}<br><br>{{ _("Keep your") }} ${capitalize(device.type)} {{ _("connected") }}.`);
        let result = [];
        try {
            result = await hwi.getXpub(device, derivation, passphrase, chain);
        } catch (error) {
            handleHWIError(error);
            return null;
        }
        if(!overlayIsActive()){
            // showNotification("HWI is ready again", 3000);
            // no need to proceed at all
            return null;
        }
        hidePageOverlay();
        return result;
    }

    async function getMasterBlindingKey(device, passphrase="", chain=""){
        // detect device
        showHWIProgress(`{{ _("Extracting master blinding key...") }}`, 
            `{{ _("Please confirm action on your") }} ${capitalize(device.type)} {{ _("device") }}.`);
        let result = [];
        try {
            result = await hwi.getMasterBlindingKey(device, passphrase, chain);
        } catch (error) {
            handleHWIError(error);
            return null;
        }
        if(!overlayIsActive()){
            // showNotification("HWI is ready again", 3000);
            // no need to proceed at all
            return null;
        }
        hidePageOverlay();
        return result;
    }

    // TODO: remove, legacy
    function onCancelOverlay(){

    }
</script>
