{% extends "wallet/components/wallet_tab.jinja" %}
{% include "includes/file-uploader.html" %}
{% include "includes/dnd-textarea.html" %}
{% set tab = 'settings' %}
{% block content %}
	<style>
		.subtitle {
			font-size: 1.4em;
			text-align: center;
		}
		.section-separator {
			border-top: 1px solid #aaa;
			margin: 40px 20px;
		}
		#blockchain-rescan {
			transition: border-color 3s;
		}
		.animation-rescan {
			padding-top: 5px;
			border: 0.5px solid orange;
			border-radius: 10px;
		}
	</style>
	<br>
	<nav class="row collapse-on-mobile">
		<button type="button" id="info_settings_tab_btn" class="btn radio left checked" onclick="setSettingsView('info')"> {{ _("Wallet Info") }} </button>
		<button type="button" id="export_settings_tab_btn" class="btn radio" onclick="setSettingsView('export')"> {{ _("Export") }} </button>
		<button type="button" id="advanced_settings_tab_btn" class="btn radio right" onclick="setSettingsView('advanced')"> {{ _("Advanced") }} </button>
		<a href="javascript:void(0);" class="mobile-nav-icon" onclick="toggleMobileNav(this, `{{ url_for('static', filename='img/caret-down.svg') }}`, `{{ url_for('static', filename='img/caret-up.svg') }}`)">
			<img style="width: 36px;" src="{{ url_for('static', filename='img/caret-down.svg') }}" class="svg-white"/>
		</a>
	</nav><br>
	<div id="wallet_info_settings_tab" style="width: 100%">
		<h1 style="font-size: 1.7em;">{{ _("Wallet Info") }}</h1><br>
		{% if wallet.is_multisig %}
			<h2 class="subtitle">{{ _("Devices") }}</h2>
			<p style="text-align: center; font-size: 1.2em;">{{ wallet.sigs_required }} out of {{ wallet.keys|length }} multisig</p>
		{% else %}
			<h2 class="subtitle">{{ _("Device") }}</h2>
		{% endif %}
		<div class="row overflow">
			{% for device in wallet.devices %}
				<a href="{{ url_for('devices_endpoint.device', device_alias=device.alias) }}" style="text-decoration: none;">
					<div class="small-card radio">
						<img src="{{ url_for('static', filename='img/devices/' ~ device.icon) }}" width="18px">
						{{ device.name }}
					</div>
				</a>
			{% endfor %}
		</div>
		<button onclick="toggleKeysList()" id="toggle_keys_list" type="button" class="btn centered padded">{{ _("Show keys details") }}</button>
		<br>
		<div id="keys_list" class="center" style="margin: auto; display: none; width: 85%;">
			<label style="font-size: 1.3em;">{{ _("Use SLIP-132:") }}&nbsp;</label>
			<label class="switch">
				<input type="checkbox" id="use_slip_132" onchange="toggleKeyDisplay()">
				<span class="slider"></span>
			</label><br>
			<p class="note" style="margin-top: 5px; max-width: 90%;">{{ _("SLIP-132 extended public keys (xpubs) are a different format for xpubs which usually starts with zpub or ypub.") }}</p>
			<br>
			{% for i in range(wallet.devices | length) %}
				{% set device = wallet.devices[i] %}
				{% set key = wallet.keys[i] %}
				<h1>{{ _("Signer") }} {% if wallet.is_multisig %}{{ loop.index }} {% endif %}- {{ device.name }}</h1>
				<div class="table-holder">
					<table>
						<thead>
							<tr>
								<th>{{ _("Network") }}</th>
								<th>{{ _("Purpose") }}</th>
								<th class="optional">{{ _("Derivation") }}</th>
								<th class="optional">{{ _("Key") }}</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>
									{% include "components/network_label.jinja" %}
								</td>
								<td>{{ purposes[key.key_type] }}</td>
								<td class="optional">{{ key.derivation }}</td>
								<td class="scroll xpub optional"><span class="normal_xpub hidden">{{ key.original }}</span><span class="slip132_xpub">{{ key.xpub }}</span></td>
							</tr>
						</tbody>
					</table>
				</div>	
				<div class="spacer"></div>
			{% endfor %}
		</div>
	</div>
	<div class="hidden" id="wallet_export_settings_tab">
		<h1 style="font-size: 1.7em;">{{ _("Export Wallet") }}</h1>
		<div class="card center">
			{% set supports_export_to_device = [] %}
			{% for device in wallet.devices if device.exportable_to_wallet %}
				{# check if export_wallet is not None #}
				{% if device.export_wallet(wallet) %}
					{% set supports_export_to_device = supports_export_to_device.append(device) %}
				{% endif %}
			{% endfor %}
			{% if supports_export_to_device != [] %}
				<h2 class="subtitle">{{ _("Export wallet to device") }}</h2>
				<p class="center">
					{{ _("Export this wallet to a device by scanning its QR code or importing its data file.") }}
				</p>

				{% for device in wallet.devices %}
					{% if device.exportable_to_wallet %}
						{% if device.wallet_export_type == 'file' %}
							<a 
							download="{{ wallet.name | ascii20 }}.txt"
							href="data:text/plain;charset=US-ASCII,{{ device.export_wallet(wallet) }}"
							{% if device.device_type == 'coldcard' %}
								onclick="showNotification(`{{ _('Import wallet file to your ColdCard: Settings -> Multisig Wallets -> Import from SD') }}`, 0)"
							{% endif %}
							class="btn centered padded">
								Save {{ device.name }} file
							</a>
						{% elif device.wallet_export_type == 'qr' %}
							<button onclick="showPageOverlay('{{ device.alias }}_export_qr_code')" type="button" class="btn centered padded">Show {{ device.name }} QR Code</button>
							<div id="{{ device.alias }}_export_qr_code" style="display: none;">
								<h1>{{ _("Scan this with your") }} {{ device.name }} {{ _("device") }} </h1>
								<qr-code value="{{ device.export_wallet(wallet) }}" width="400" scalable></qr-code>
							</div>
						{% endif %}
					{% endif %}
				{% endfor %}
				<div class="section-separator"></div>
			{% endif %}
			
			<h2 class="subtitle">{{ _("Export to wallet software") }}</h2>
			<p class="center">
				{{ _("Export this wallet to another Specter instance or other supported wallet softwares by scanning the QR code or importing the JSON file.") }}
			</p>
			<button onclick="showPageOverlay('account_map_export')" type="button" class="btn centered padded">{{ _("Go to export details") }}</button>
			<div class="section-separator"></div>
			<h2 class="subtitle">{{ _("Specter wallet backup") }}</h2>
			<p class="center">
				{{ _("Create a JSON file containing all wallet data including labels.") }}
			</p>
			<a download="{{ wallet.name }}.json" class="btn centered padded" id="export_specter_format">Download Specter JSON file</a>
			<div class="section-separator"></div>
			<div class="row center" style="align-items: center;">
				<h2 class="subtitle">{{ _("Printable PDF backup") }}</h2>
				<tool-tip width="180px">
				    <span slot="paragraph">
				    	{{ _("This backup includes all the information you need to restore your wallet in Specter Desktop or other compatible wallets including Bitcoin Core.") }}
	    				{{ _("It is recommended that you keep this file private. It contains all the information to track your balance and associate transactions with your wallet.") }}
				    </span>
				</tool-tip>
			</div>
			<p style="max-width: 500px;" class="center">
			{{ _("It is recommended that you print this backup and save it with each of your devices.") }}
			</p>
			<button id="pdf-wallet-download" type="button" class="btn centered padded" style="margin: 30px auto;">Open backup PDF</button>
			<span id="advanced_pdf_export_toggle" style="cursor: pointer;" onclick="togglePDFExportAdvanced()">{{ _("Adjust PDF backup (advanced)") }} &#9654;</span>
			<div style="margin: 20px;" class="center hidden" id="advanced_pdf_export_container">
				<div class="row center">
					<label style="font-size: 1em;">{{ _("Use SLIP-132 for xpubs in PDF:") }}&nbsp;</label>
					<label class="switch">
						<input type="checkbox" id="use_slip_132_pdf" style="margin: auto;" onchange="toggleKeyDisplay()">
						<span class="slider"></span>
					</label>
				</div>
			</div>
			{% if not wallet.is_multisig %} 
			<div class="section-separator"></div>
			<div class="row center" style="align-items: center;">
				<h2 class="subtitle">{{ _("Uncle Jim PDF") }}</h2>
				<tool-tip width="180px">
				    <span slot="paragraph">
						{{ _('The PDF lists many singlesig addresses in QR code format, as well as the descriptor of the wallet as a QR code with which the wallet can be imported to Specter Desktop at any time.') }}
						{{ _('There are checkboxes to keep track of which addresses were used already.') }}
						{{ _('Can be folded into DIN-A5 to fit in a transparent sealing bag (together with the seed).') }}
				    </span>
				</tool-tip>
			</div>
				<p class="center"> {{ _("PDF optimized for Uncle Jims: hand out addresses to receive funds for friends & family without hardware wallet.") }}</p>
				<button id="pdf-paperxpub-download" type="button" class="btn centered padded" style="margin: 30px auto;">
					Get Uncle Jim PDF
				</button>
			{% endif %}
			{% include 'wallet/components/wallet_pdf.jinja' %}
			{% include "wallet/settings/components/export_wallet_account_map.jinja" %}
		</div>
	</div>
	<div class="hidden" id="wallet_advanced_settings_tab">
		<h1 style="font-size: 1.7em;">{{ _("Advanced Options") }}</h1>
		<div class="card">
			<h2 class="subtitle">{{ _("Import address labels (Electrum or Specter)") }}</h2>
			<form action="." method="POST" class="padded" style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				<div class="row aligned">
					<dnd-textarea 
						name="address_labels_data" 
						id="address_labels_data" 
						placeholder="{{ _('You can paste and drag & drop here:') }}&#10&#10{{ _('Electrum JSON file, Specter addresses CSV or Specter JSON file') }}"  
						textarea-style="margin-bottom: 10px;">
					</dnd-textarea>
					<file-uploader id="label-uploader" image_src="{{ url_for('static', filename='img/file.svg') }}" image_width="30px" button_width="137px" button_height="50px" button_color="hsl(217, 20%, 35%)">
						<span slot="description">or upload file</span>
					</file-uploader>
				</div>
				<div class="row center">
					<button type="submit" name="action" value="import_address_labels" class="btn" style="max-width: 130px; margin-left: 20px">{{ _("Import") }}
						<tool-tip width="200px">
							<span slot="paragraph">
								{{ _('The expected format for Electrum contains:') }}<br>
								{{ _('{"8a5e4...": "some tx id label", "bc1qj3...": "some address label"}') }}<br><br>
								{{ _('The expected format for Specter JSON contains:') }}<br>
								{{ _('{"labels": {"some_label": ["bc1qj3..."], ...}') }}<br><br>
								{{ _('The expected format for Specter CSV contains:') }}<br>
								{{ _('Address,Label') }}<br>
								{{ _('bc1qj3...,some_label') }}<br> 
							</span>
						</tool-tip>
					</button>
				</div>
			</form>
			<div class="section-separator"></div>
			<h2 class="subtitle">{{ _("Keypool control") }}</h2>
			<form action="." method="POST" class="padded" style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				<div>{{ _("Currently watching") }} {{ wallet.keypool }} {{ _("receiving and") }} {{ wallet.change_keypool }} {{ _("change addresses.") }}</div>
				<div class="row aligned">
					<div style="flex-grow: 1">{{ _("Watch") }} <input type="number" name="keypooladd" value="100" step="1" style="margin: 10px" class="inline"> {{ _("more addresses") }} </div>
					<button type="submit" name="action" value="keypoolrefill" class="btn" style="max-width: 130px; margin-left: 20px">{{ _("Add") }}</button>
				</div>
			</form>
			<div class="section-separator"></div>
			<h2 class="subtitle" id="blockchain-rescan">{{ _("Blockchain rescan") }}</h2>
			<form action="." method="POST" class="padded" style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				{% if wallet.rescan_progress %}
					<div class="row aligned">
						<div style="margin-right: 30px; flex-grow: 1;">{{ _("Rescanning blockchain:") }} <span id="{{ wallet.alias }}_wallet_rescan_percents">{{"%.2f" % (wallet.rescan_progress*100)}}</span>%</div>
						<button type="submit" name="action" value="abortrescan" class="btn" style="max-width: 130px; margin-left: 20px">{{ _("Abort rescan") }}</button>
					</div>
				{% else %}
					{{ _("Rescan blockchain from block:") }}<br>
					<div class="row aligned" style="justify-content: space-between;">
						{% if specter.info.chain == "main" %}
							{% if wallet.is_taproot %}
								{% set startblock=(709632 if not specter.info['pruned'] or specter.info['pruneheight'] < 709632 else specter.info['pruneheight']) %}
							{% else %}
								{% set startblock=(481824 if not specter.info['pruned'] or specter.info['pruneheight'] < 481824 else specter.info['pruneheight']) %}
							{% endif %}
						{% else %}
							{% set startblock=(0 if not specter.info['pruned'] else specter.info['pruneheight']) %}
						{% endif %}
						<input type="number" name="startblock" value="{{startblock}}" style="flex-basis: 220px;" min="{{startblock}}">
						<button id="rescan-btn" type="submit" name="action" value="rescanblockchain" class="btn" style="flex-basis: 170px; flex-grow: 0;">{{ _("Rescan") }}</button>
					</div>
					{% if specter.info['pruned']  %}
						<div class="note full-width">{{ _("Note: You are using a pruned node. Rescan is limited by the pruned height to block:") }} {{specter.info['pruneheight']}}</div>
					{% endif %}
					{% if wallet.is_taproot %}
						<div class="note"><b>709632</b> {{ _("was the first Taproot block.") }}</div>
					{% else %}
						<div class="note"><b>481824</b> {{ _("was the first Segwit block.") }}</div>
					{% endif %}
				{% endif %}
			</form>
			<form action="." method="POST" class="padded" style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				{% if specter.info["utxorescan"] %}
				<div class="row aligned padded">
					<div style="flex-grow: 1">{{ _("UTXO rescan in process:") }} <span id="wallet_rescan_percents">{{ "%.2f"|format(specter.info["utxorescan"]) }}</span>%.</div>
					<button type="submit" name="action" value="abortrescanutxo" class="btn" style="max-width: 130px; margin-left: 20px">{{ _("Abort rescan") }}</button>
				</div>
				{% else %}
				<div class="row aligned" style="justify-content: space-between;">
					<div style="flex-grow: 1">{{ _("Or rescan only unspent transactions:") }}
					</div>
					<button id="rescan-utxo-btn" type="submit" name="action" value="rescanutxo" class="btn" style="flex-grow: 0; max-width: 170px; max-height: 35.5px">
						{{ _("Rescan UTXO") }}
						<tool-tip width="150px" image="note">
        					<h4 slot="title">{{ _("Rescanning UTXO set") }}</h4>
					        <span slot="paragraph">
								{{ _("Only unspent transactions will be imported, so you won't see the full history, but your balance will be there.") }}<br>
								<b>{{ _("Note:") }}</b> {{ _("Make sure you have enough addresses in the keypool, otherwise not all unspent transactions may be found.") }}
					        </span>
					    </tool-tip>
					</button>
				</div>
				{% if specter.info['pruned'] %}
					<div class="row" style="margin-top: 10px">
						<label for="use_explorer"><input style="width: auto; min-width: auto;" type="checkbox" id="use_explorer" name="use_explorer" checked> {{ _("fetch missing data from block explorer") }}
						</label>
						<tool-tip width="150px" image="note">
						    <h4 slot="title">{{ _("Fetch missing data") }}</h4>
						    <span slot="paragraph">
						    	{{ _("You are using a pruned node. Blocks for some transactions may be missing.") }}<br><br>
								{{ _("Check this checkbox if you want to fetch missing information from block explorer.") }}
						    </span>
						</tool-tip>
					</div>
					<div id="utxo-explorer">
						<br>
						{{ _("Block explorer URL:") }}
						{% include "components/explorer_select.jinja" %}
						<span class="warning" id="utxo-warning" style="display: inline-block; max-width:300px;">
							<img src="{{ url_for('static', filename='img/info_sign.svg') }}" style="width: 20px;"/><br>{{ _("Careful with block explorers!") }}<br>
							{{ _("This may have privacy implications!") }}<br>
							{{ _("Information fetched from the block explorer contains a list of unspent transactions of your wallet from old (pruned) blocks.") }}<br>
							{{ _('"They" will know what transactions you are interested in.') }}
						</span>
					</div>
					<script type="text/javascript">
						let utxocheckbox = document.getElementById("use_explorer");
						utxocheckbox.addEventListener('change', e=>{
							let el = document.getElementById("utxo-explorer")
							if(utxocheckbox.checked){
								el.style.display = "block";
							}else{
								el.style.display = "none";
							}
						});
					</script>
				{% endif %}

				{% endif %}
			</form>
			<div class="section-separator"></div>
			<h2 class="subtitle">{{ _("Delete wallet") }}</h2>
			<form action="." method="POST" class="padded" style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				<button type="submit" id="delete_wallet" name="action" value="deletewallet" class="btn danger centered" style="max-width: 160px;">{{ _("Delete Wallet") }}</button>
			</form>
		</div>
	</div>
	<br><br>
{% endblock %}

{% block scripts %} 
	<script type="text/javascript">
		
		let uploader = document.getElementById('label-uploader');
		uploader.addEventListener('upload', e => {
			let result = e.detail.result;
			console.log(result);
			document.getElementById("address_labels_data").value = result;
		});

		document.addEventListener("DOMContentLoaded", function(){
			let walletDataSpecterFormat = encodeURIComponent(`{{ wallet.to_json(for_export=True)|tojson }}`);
			document.getElementById('export_specter_format').href = "data:text/json;charset=utf-8," + walletDataSpecterFormat;
		});

		function toggleKeysList() {
			let titleButton = document.getElementById('toggle_keys_list');
			let keysList = document.getElementById('keys_list');
			if (keysList.style.display !== 'none') {
				keysList.style.display = 'none';
				titleButton.innerHTML = `{{ _("Show keys details") }}`;
			} else {
				keysList.style.display = 'block';
				titleButton.innerHTML = `{{ _("Hide keys details") }}`;
			}
		}

		function toggleKeyDisplay() {
			let slip132Checkbox = document.getElementById('use_slip_132');
			let xpubs = document.getElementsByClassName('slip132_xpub');
			let zpubs = document.getElementsByClassName('normal_xpub');
			if (slip132Checkbox.checked) {
				for (xpub of xpubs) {
					xpub.style.display = 'none';
				}
				for (zpub of zpubs) {
					zpub.style.display = 'block';
				}
			} else {
				for (xpub of xpubs) {
					xpub.style.display = 'block';
				}
				for (zpub of zpubs) {
					zpub.style.display = 'none';
				}
			}
		}

		function togglePDFExportAdvanced() {
			let advancedButton = document.getElementById(`advanced_pdf_export_toggle`);
			let advancedSettings = document.getElementById(`advanced_pdf_export_container`);
			if (advancedSettings.classList.contains("hidden")) {
				advancedSettings.classList.remove("hidden");
				advancedButton.innerHTML = `{{ _("Adjust PDF backup (advanced)") }} &#9660;`;
			} else {
				advancedSettings.classList.add("hidden");
				advancedButton.innerHTML = `{{ _("Adjust PDF backup (advanced)") }} &#9654;`;
			}
		}

		function setSettingsView(view) {
            let infoSettingsTab = document.getElementById("wallet_info_settings_tab");
            let exportSettingsTab = document.getElementById("wallet_export_settings_tab");
            let advancedSettingsTab = document.getElementById("wallet_advanced_settings_tab");
            let infoSettingsTabBtn = document.getElementById("info_settings_tab_btn");
            let exportSettingsTabBtn = document.getElementById("export_settings_tab_btn");
            let advancedSettingsTabBtn = document.getElementById("advanced_settings_tab_btn");
            switch (view) {
				case 'info':
					infoSettingsTab.style.display = 'block';
					exportSettingsTab.style.display = 'none';
					advancedSettingsTab.style.display = 'none';
					infoSettingsTabBtn.className = infoSettingsTabBtn.className += ' checked';
					exportSettingsTabBtn.className = exportSettingsTabBtn.className.replace(/checked/, '');
					advancedSettingsTabBtn.className = advancedSettingsTabBtn.className.replace(/checked/, '');
					break;
				case 'export':
					infoSettingsTab.style.display = 'none';
					exportSettingsTab.style.display = 'block';
					advancedSettingsTab.style.display = 'none';
					infoSettingsTabBtn.className = infoSettingsTabBtn.className.replace(/checked/, '');
					exportSettingsTabBtn.className = exportSettingsTabBtn.className += ' checked';
					advancedSettingsTabBtn.className = advancedSettingsTabBtn.className.replace(/checked/, '');
					break;
				case 'advanced':
					infoSettingsTab.style.display = 'none';
					exportSettingsTab.style.display = 'none';
					advancedSettingsTab.style.display = 'block';
					infoSettingsTabBtn.className = infoSettingsTabBtn.className.replace(/checked/, '');
					exportSettingsTabBtn.className = exportSettingsTabBtn.className.replace(/checked/, '');
					advancedSettingsTabBtn.className = advancedSettingsTabBtn.className += ' checked';
					break;
            }
        }

        let textarea = document.getElementById("address_labels_data");
		document.addEventListener('file-upload', e => {
			let result = e.detail.result;
			textarea.value = result;
		})

		// Makes sure that the textarea for labels is cleared
		document.addEventListener("DOMContentLoaded", () => {
			let textarea = document.getElementById("address_labels_data");
			textarea.value = "";
		})

	    function scrolltoRescanBlockchain() {
			setSettingsView("advanced");
			document.getElementById('blockchain-rescan').scrollIntoView();
		}
		// Only called when the user comes from an empty tx list to rescan
		{% if scroll_to_rescan_blockchain %}
	        scrolltoRescanBlockchain();
	       	document.getElementById('blockchain-rescan').classList.add("animation-rescan")
	    {% endif %}
	</script>

{% endblock %}
