{% extends "base.jinja" %}

{% block main %}
    <style>
        .wizard-btn {
            width: 200px;
            min-width: 200px;
            max-width: 200px;
            height: 36px;
            margin: auto;
        }
        .helper-btn {
            text-decoration: underline;
            margin: 10px 50px;
        }
    </style>
    {% from "components/bitcoin_svg.jinja" import bitcoin_svg %}
    <div class="card center hidden" id="step0">
        <h1>Specter Quickstart!</h1>
        <h2>Get up and running with Specter in just a few clicks!</h2><br>
        <img style="width: 50px;" src="{{ url_for('static', filename='img/tor.svg') }}"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        {{ bitcoin_svg('main', 50) }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <img src="{{ url_for('static', filename='img/icon.png') }}" style="width: 50px;"/>
        <br><br>
        <p style="max-width: 400px; margin: auto;">
            Here, we'll take you through the process of setting up Specter with your own Bitcoin Core node and Tor.<br><br>
            Everything is completely automated, but you make choices to customize your setup to fit your needs.
        </p>
        <br><br>
        <div class="row">
            <button type="button" class="btn wizard-btn action" onclick="showStep(1)">Get Started!</button>
        </div>
    </div>
    <div class="card center hidden" id="step1">
        <h1><img src="{{ url_for('static', filename='img/icon.png') }}" style="width: 60px;"/> <img src="{{ url_for('static', filename='img/arrow_right.svg') }}" style="width: 60px;"/>&nbsp;<img style="width: 60px;" src="{{ url_for('static', filename='img/tor.svg') }}"/><br>
        <br>Download and setup Tor daemon</h1>
        <h2 style="color: #ccc;">(optional, recommended)</h2>
        <p>This should take between a few seconds to a few minutes, depending on your internet connection...</p>
        <p class="hidden warning" id="step1-helper-text">Here, Specter will download the Tor daemon software, verify signatures to ensure download files can be trusted, and start your Tor daemon to allow you to make calls over the Tor network.</p>
        <div class="row center">
            <p class="explorer-link" id="step1-helper" onclick="toggleHelper('step1')">Unsure? Click here for more info!</p>
            <a class="explorer-link hidden" id="step1-support" href="https://t.me/spectersupport" target="_blank">Still need help?</a>
        </div>
        <br><br>
        <div class="row">
            <button type="button" class="btn wizard-btn" onclick="showStep(2)">Skip</button>
            <button type="button" class="btn wizard-btn action" id="setup-tor-button" onclick="setupTorDaemon()">Setup Tor!</button>
        </div>
    </div>
    <div class="card center hidden" id="step2">
        <h1><img src="{{ url_for('static', filename='img/icon.png') }}" style="width: 60px;"/> <img src="{{ url_for('static', filename='img/arrow_right.svg') }}" style="width: 60px;"/>&nbsp;{{ bitcoin_svg('main', 60) }}<br>
        <br>Would you like to setup a new Bitcoin node or connect to an existing one?</h1>
        <p class="hidden warning" id="step2-helper-text">If you have an existing Bitcoin Core node you would like to use, either running locally on this computer or somewhere else, like on Umbrel, myNode, or RaspiBlitz, you can just connect and use it.<br><br>
        Don't have a node? Specter can help you setup a new one! This guide will help you get it up and running!</p>
        <div class="row center">
            <p class="explorer-link" id="step2-helper" onclick="toggleHelper('step2')">Unsure? Click here for more info!</p>
            <a class="explorer-link hidden" id="step2-support" href="https://t.me/spectersupport" target="_blank">Still need help?</a>
        </div>
        <br><br>
        <div class="row">
            <a href="{{url_for('settings_endpoint.bitcoin_core')}}" class="btn wizard-btn">Connect existing node</a>
            <button type="button" class="btn wizard-btn action" onclick="showStep(3)">Setup a new node</button>
        </div>
    </div>
    <div class="card center hidden" id="step3">
        <h1><img src="{{ url_for('static', filename='img/icon.png') }}" style="width: 60px;"/> <img src="{{ url_for('static', filename='img/arrow_right.svg') }}" style="width: 60px;"/>&nbsp;{{ bitcoin_svg('main', 60) }}<br>
        <br>Download and setup Bitcoin Core</h1>
        <p>This should take between a few seconds to a few minutes, depending on your internet connection...</p>
        <p class="hidden warning" id="step3-helper-text">Here, Specter will download the Bitcoin Core release software, verify signatures to ensure download files can be trusted, and prepare basic configurations of your new Bitcoin Core node.</p>
        <div class="row center">
            <p class="explorer-link" id="step3-helper" onclick="toggleHelper('step3')">Unsure? Click here for more info!</p>
            <a class="explorer-link hidden" id="step3-support" href="https://t.me/spectersupport" target="_blank">Still need help?</a>
        </div><br>
        <span id="toggle_advanced_3" style="cursor: pointer;" onclick="toggleAdvanced(3)">Advanced &#9654;</span>
        <br>
        <br>
        <div id="advanced_settings_3" class="card hidden">
            <h2 style="text-decoration: underline;">Advanced configurations</h2><br>
            <p style="text-align: left;">
            Bitcoin Core data directory path:<br>
            <input type="text" id="bitcoin_core_datadir" name="bitcoin_core_datadir" type="text" value="{{ specter.config.rpc.datadir }}">
            </p>
        </div>
        <br><br>
        <div class="row">
            <button type="button" class="btn wizard-btn action" id="setup-bitcoind-button" onclick="setupBitcoind()">Start the Setup!</button>
        </div>
    </div>
    <div class="card center hidden" id="step4">
        <h1><img src="{{ url_for('static', filename='img/icon.png') }}" style="width: 60px;"/> <img src="{{ url_for('static', filename='img/arrow_right.svg') }}" style="width: 60px;"/>&nbsp;{{ bitcoin_svg('main', 60) }}<br>
        <br>Configure your node</h1>
        <p>QuickSync?&nbsp;&nbsp;
            <label class="switch">
                <input type="checkbox" name="quicksync" id="quicksync" onchange="toggleNodeTypeSelect()" checked>
                <span class="slider"></span>
            </label>&nbsp;&nbsp;
            <tool-tip title="What is QuickSync?">
                QuickSync will set up your new node from a trusted state of the blockchain.<br><br>
                This means all block validation will be skipped until the most recent block in the snapshot.<br><br>
                Later blocks will be normally validated like with a regular full node.
            </tool-tip>
        </p>
        <div class="hidden" id="select-node-type-div">
            <br>
            <h1>Select node type:</h1>
            <div class="row">
                <label style="position: relative;">
                    <input type="radio" name="node-type" id="node-type-archival" class="hidden" value="archival">
                    <div class="small-card radio">
                        <span style="font-size: 1.2em; font-weight: bold;">Archival Node</span><br>
                        Requires about 400GB of available storage
                    </div>
                </label>
                <label style="position: relative;">
                    <input type="radio" name="node-type" class="hidden" value="pruned" checked>
                    <div class="small-card radio">
                        <span style="font-size: 1.2em; font-weight: bold;">Pruned Node</span><br>
                        Requires about 10GB of available storage<br><br>
                    </div>
                </label>
            </div>
        </div>
        <p class="hidden warning" id="step4-helper-text">
            Now that you have Bitcoin Core installed, your next step will be to sync with the network.<br><br>
            Specter allows you to choose between normal syncing (IBD) - which will download and validate the entire history of the blockchain, or downloading a trusted snapshot of the current state of the network.<br><br>
            This snapshot is produced and signed by Specter team - which means you will be trusting it to get the present state of the blockchain, instead of verifying the history yourself.<br><br>
            It takes about 5GB to download and will setup a fully synced pruned node for you to use.
            You can also disable the QuickSync option, and choose between setting up an archival node (which keeps the entire history) or a pruned node.<br><br>
            <b>Please note: it is recommended to use a full archival node, or if storage is a constraint, a pruned node synced from scratch. The option for QuickSync is useful for getting started quickly, but is not recommended in the long term or when using Specter with large amounts.</b>
        </p>
        <div class="row center">
            <p class="explorer-link" id="step4-helper" onclick="toggleHelper('step4')">Unsure? Click here for more info!</p>
            <a class="explorer-link hidden" id="step4-support" href="https://t.me/spectersupport" target="_blank">Still need help?</a>
        </div>
        <br><br>
        <div class="row">
            <button type="button" class="btn wizard-btn action" id="setup-bitcoind-dir-button" onclick="setupBitcoindDirectory()">Start Syncing!</button>
        </div>
    </div>
    <div class="card center hidden" id="step5">
        <img style="width: 100px;" src="{{ url_for('static', filename='img/party.png') }}"/><br><br>
        <h1 style="font-size: 1.8em;">Setup Completed Successfully!</h1>
        <p>Your new node is up and running!</p><br>
        <a href="{{url_for('about')}}" class="btn wizard-btn action">Done</a>
    </div>
    <br>
    <button type="button" class="btn hidden action" id="show-progress-details" style="max-height: 36px;" onclick="showPageOverlay('stage-progress-details');">View Progress</button>
    <h1 id="stage-progress-details" class="hidden" style="margin: auto;"></h1>
    <br><br>
{% endblock %}


{% block scripts %}
    <script>
        let currentStep = parseInt('{{step}}');
        let torSetup = false;
        document.addEventListener("DOMContentLoaded", function(){
            showStep(currentStep);
        });

        function showStep(step) {
            currentStep = step;
            document.getElementById('step0').classList.add('hidden');
            document.getElementById('step1').classList.add('hidden');
            document.getElementById('step2').classList.add('hidden');
            document.getElementById('step3').classList.add('hidden');
            document.getElementById('step4').classList.add('hidden');
            document.getElementById('step5').classList.add('hidden');
            document.getElementById(`step${step}`).classList.remove('hidden');
        }

        function toggleHelper(step) {
            let helper = document.getElementById(step + "-helper");
            let helperText = document.getElementById(step + "-helper-text");
            let support = document.getElementById(step + "-support");
            if (helperText.classList.contains("hidden")) {
                helper.innerText = "Got it!";
                helperText.classList.remove("hidden");
                support.classList.remove("hidden");
                helper.classList.add("helper-btn");
                support.classList.add("helper-btn");
            } else {
                helper.innerText = "Unsure? Click here for more info!";
                helperText.classList.add("hidden");
                support.classList.add("hidden");
                helper.classList.remove("helper-btn");
                support.classList.remove("helper-btn");
            }
        }

        function toggleAdvanced(step) {
            let advancedButton = document.getElementById(`toggle_advanced_${step}`);
            let advancedSettings = document.getElementById(`advanced_settings_${step}`);
            if (advancedSettings.classList.contains("hidden")) {
                advancedSettings.classList.remove("hidden");
                advancedButton.innerHTML = 'Advanced &#9660;';
            } else {
                advancedSettings.classList.add("hidden");
                advancedButton.innerHTML = 'Advanced &#9654;';
            }
        }

        function toggleNodeTypeSelect() {
            let nodeTypeDiv = document.getElementById('select-node-type-div');
            if (document.getElementById('quicksync').checked) {
                nodeTypeDiv.classList.add('hidden');
            } else {
                nodeTypeDiv.classList.remove('hidden');
            }
        }

        async function setupTorDaemon() {
            torSetup = true;
            let url = "{{ url_for('setup_tor') }}"
            var formData = new FormData();
            formData.append('csrf_token', '{{ csrf_token() }}');
            try {
                const response = await fetch(
                    url,
                    {
                        method: 'POST',
                        body: formData
                    }
                );
                if(response.status != 200){
                    showError(await response.text());
                    return;
                }
                const jsonResponse = await response.json();
                if ("success" in jsonResponse) {
                    showNotification(jsonResponse.success);
                    document.getElementById('setup-tor-button').classList.add('hidden');
                    startProgressCheck();
                    return;
                } if (jsonResponse.error == "tor is already installed") {
                    showNotification('Tor already installed, skipped step.');
                    showStep(++currentStep);
                    return;
                }
                showError(jsonResponse.error, 4000);
            }  catch(e) {
                showError("Failed to download Tor daemon...");
                showError(e);
            }
        }

        async function setupBitcoind() {
            torSetup = false;
            let url = "{{ url_for('setup_bitcoind') }}"
            var formData = new FormData();
            formData.append('csrf_token', '{{ csrf_token() }}');
            formData.append('bitcoin_core_datadir', document.getElementById('bitcoin_core_datadir').value);
            try {
                const response = await fetch(
                    url,
                    {
                        method: 'POST',
                        body: formData
                    }
                );
                if(response.status != 200){
                    showError(await response.text());
                    return;
                }
                const jsonResponse = await response.json();
                if ("success" in jsonResponse) {
                    showNotification(jsonResponse.success);
                    document.getElementById('setup-bitcoind-button').classList.add('hidden');
                    startProgressCheck();
                    return;
                } if (jsonResponse.error == "bitcoind already installed") {
                    showNotification('Bitcoin Core already installed, skipped step.');
                    showStep(++currentStep);
                    return;
                }
                showError(jsonResponse.error, 4000);
            }  catch(e) {
                showError("Failed to download Bitcoin Core...");
                showError(e);
            }
        }

        async function setupBitcoindDirectory() {
            torSetup = false;
            let url = "{{ url_for('setup_bitcoind_directory') }}"
            var formData = new FormData();
            formData.append('csrf_token', '{{ csrf_token() }}');
            formData.append('quicksync', document.getElementById('quicksync').checked);
            formData.append('nodetype', document.getElementById('node-type-archival').checked ? 'archival' : 'pruned');
            try {
                const response = await fetch(
                    url,
                    {
                        method: 'POST',
                        body: formData
                    }
                );
                if(response.status != 200){
                    showError(await response.text());
                    return;
                }
                const jsonResponse = await response.json();
                if ("success" in jsonResponse) {
                    showNotification(jsonResponse.success);
                    document.getElementById('setup-bitcoind-dir-button').classList.add('hidden');
                    startProgressCheck();
                    return;
                }
                showError(jsonResponse.error, 4000);
            }  catch(e) {
                showError("Failed to start Bitcoin Core...");
                showError(e);
            }
        }

        function startProgressCheck() {
            async function fetchStageProgress() {
                try {
                    let url = "{{ url_for('get_node_setup_status') }}"

                    if (torSetup) {
                        url = "{{ url_for('get_tor_setup_status') }}"
                    }
                    const response = await fetch(
                        url,
                        {
                            method: 'GET'
                        }
                    );
                    let result = await response.json();
                    if (result.error) {
                        showError('Encountered an error:' + result.error);
                        document.getElementById('stage-progress-details').classList.add('hidden');
                        hidePageOverlay('stage-progress-details');
                        return;
                    }
                    let stage = result.stage;
                    let progress = parseFloat(result.stage_progress);
                    if (progress == -1) {
                        showNotification('Finished successfully');
                        showStep(++currentStep);
                        document.getElementById('stage-progress-details').classList.add('hidden');
                        document.getElementById('show-progress-details').classList.add('hidden');
                        hidePageOverlay('stage-progress-details');
                        return;
                    }
                    document.getElementById('stage-progress-details').innerHTML = `${stage}<br>`;
                    if (progress > 0) {
                        document.getElementById('stage-progress-details').innerHTML += `<br><br><b style="font-size:0.8em;">Progress: ${progress}%</b>`;
                    }
                    setTimeout(fetchStageProgress, 1000);
                } catch(e) {
                    console.log('Caught error:', e);
                    return { success: false, error: e };
                }
            }
            document.getElementById('stage-progress-details').classList.remove('hidden');
            document.getElementById('show-progress-details').classList.remove('hidden');
            showPageOverlay('stage-progress-details');
            document.getElementById('stage-progress-details').innerHTML = 'Stating up...';
            
            setTimeout(fetchStageProgress, 1000);
        }
    </script>
{% endblock %}
