{% extends "base.jinja" %}
{% block main %}
	{% include "includes/overlay/key_export_qr.jinja" %}
	{% include "includes/hwi/hwi.jinja" %}
	{% include "includes/qr-scanner.html" %}
	<style>
		#keys-table td {
			padding: 5px 20px;
		}
		#keys-table th {
			padding: 20px 20px;
		}
		.signature {
			background-color: var(--cmap-bg-lightest);
        	word-break: break-all;
        	margin-top: 5px;
        	margin: 1px;
        	border-radius: 10px;
        	border: 2px solid hsl(217, 10%, 80%);
        	padding: 10px 10px 10px 10px;
        	cursor: pointer;
		}
		.signature:hover {
			border: 2px solid var(--main-color);
		}
		.btn {
			margin-bottom: 5px;
		}
	</style>
	<h1 id="title">{{ device.name }}</h1>
	{% from 'components/editable_title.jinja' import editable_title %}
	{{ editable_title(device.name) }}
	<form action="./" method="POST" style="margin-bottom: 15px;">
		<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
		<div class="row" style="text-align: center; line-height: 2;">
			{% include "device/components/device_type.jinja" %}
		</div>
		<button type="submit" class="btn hidden" id="settype" name="action" value="settype" style="margin: auto; margin-top: 10px; align-self:center;">{{ _("Update") }}</button>
	</form>
	<br>
	<div class="table-holder">
		<table id="keys-table">
			<thead>
				<tr>
					<th>{{ _("Network") }}</th><th>{{ _("Purpose") }}</th><th class="optional">{{ _("Derivation") }}</th><th class="mobile-only">{{ _("Export") }}</th><th class="optional"></th><th class="optional">{{ _("Key") }}</th><th class="optional">{{ _("Actions") }}</th>
				</tr>
			</thead>
			<input type="hidden" id="key_selected" value="0" />
			<tbody>
				{% for key in device.keys %}
					<tr>
						<td>
						    {% include "components/network_label.jinja" %}
						</td>
						<td>{{ key.purpose }}</td>
						<td class="optional">{{ key.derivation }}</td>
						{% if specter.hide_sensitive_info %}
							<td></td>
						{% else %}
							<td width="15" onclick="showPageOverlay('key_export_qr');document.getElementById('key_selected').value='{{loop.index0}}';toggleKeyDisplay();" title="{{ _('Show key QR code') }}" style="cursor: pointer;">
								<img style="margin-top: 5px; width: 40px;" src="{{ url_for('static', filename='img/qr-code.svg') }}" class="svg-white"/>
							</td>
						{% endif %}
						<td class="xpub scroll optional">
							{% if specter.hide_sensitive_info %}
								<span class="explorer-link">##################################################</span>
							{% else %}
								<span class="explorer-link" onclick="copyText('{{ key }}', 'Copied key: {{ key }}')">{{ key }}</span>
							{% endif %}
						</td>
						<td width="80px" class="optional">
							<form action="./" method="POST">
								<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
								<input type="hidden" name="key" value="{{ key.original }}">
								<button type="submit" name="action" value="delete_key" class="btn danger hovering">{{ _("Delete") }}</button>
							</form>
						</td>
					</tr>
				{% endfor %}
			</tbody>
		</table>
	</div>
	<div style="line-height: 1; margin-top: 30px;">
		<form action="./" method="POST">
			<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
			{% if device.device_type != "bitcoincore_watchonly"%}
				<button id="add_keys" type="submit" name="action" value="add_keys" class="btn centered">{{ _("Add more keys") }}</button>
			{% else %}
				<button id="add_keys" type="submit" name="action" value="add_keys" class="btn centered">{{ _("Convert to hot wallet") }}</button>
			{% endif %}
		</form>
		{% if device.hwi_support or device.device_type == "specter" %}
		<button type="button" class="btn centered" onclick="showPageOverlay('message-signing')">{{ _("Sign message") }}</button>
		<div id="message-signing" class="hidden" style="text-align: left; max-width: 350px;">
			{% if origin %}
				{{ _("Address") }}:<input type="text" id="signing-address" type="text" value="" placeholder="bc1q ..."><br><br>
			{% endif %}
			{{ _("Derivation path") }}:<input type="text" id="messageDerivationPath" type="text" value="" placeholder="e.g. m/84h/0h/0h/0/0"><br><br>
			{{ _("Message") }}:<br>
			<textarea id="message" placeholder="Enter the message you would like to sign" style="font-size: 0.95em; margin-bottom: 15px;"></textarea>
			<span id="signature-label" class="hidden">{{ _("Message signature") }}:</span>
			<p id="signature" title='{{ _("Copy signature") }}' class="hidden" onclick="copyText(this.innerText, '{{ _("Copied message signature") }}')">
			</p>
			{% if device.hwi_support %}
				<button id="{{ device.alias }}_usb_sign_msg_btn" type="button" class="btn centered" onclick="signMessageOnDevice();">{{ _("Sign message via USB") }}</button>
			{% endif %}
			{% if device.device_type == "specter" %}
				{% include "includes/overlay/qr_code_sign_message.jinja" %}
            	<button id="{{ device.alias }}_qr_sign_msg_btn" class="btn centered" style="margin-top: 10px;">{{ _("Sign message via QR code") }}</button>
			{% endif %}
		</div>
		{% endif %}
		{% if specter.is_liquid %}
			<br>
			<a class="btn centered" href="{{ url_for('devices_endpoint.device_blinding_key', device_alias=device.alias) }}">{{ _("Update master blinding key") }}</a>
		{% endif %}
		{% if device.supports_hwi_toggle_passphrase %}
			<button type="button" class="btn centered" onclick="togglePassphrase('{{ device.device_type }}')">{{ _("Toggle device passphrase") }}</button>
			<br>
		{% endif %}
		<form action="./" method="POST">
			<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
			<button type="submit" name="action" value="forget" class="btn danger centered" id="forget_device">{{ _("Forget the device") }}</button>
		</form>
	</div>
	<br>
	{% if wallets %}
		<h1>{{ _("Wallets Using This Device") }}</h1>
		<div class="row overflow">
			{% for wallet in wallets %}
				<a href="{{ url_for('wallets_endpoint.wallet', wallet_alias=wallet.alias) }}" style="text-decoration: none;">
					<div class="small-card radio">
						<img src="{{ url_for('static', filename='img/' + ('two-keys' if wallet.is_multisig else 'key') + '.svg') }}" class="svg-white" style="width: 120px;">
						{{ wallet.name }}
					</div>
				</a>
			{% endfor %}
		</div>
	{% endif %}
	<div class="hidden" id="new_device_popup">
		<h1>{{ _("New device was added successfully!") }}</h1>
		<div class="row overflow">
			<a href="{{ url_for('devices_endpoint.new_device_type') }}" style="text-decoration: none;">
				<div class="small-card radio">
					<img src="{{ url_for('static', filename='img/plus.svg') }}" class="svg-white" style="transform: scale(1.5);">
					{{ _("Add another device") }}
				</div>
			</a>
			<form action="{{ url_for('wallets_endpoint.new_wallet', wallet_type='simple') }}" method="POST">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				<input type="hidden" name="device" value="{{ device.alias }}" />
				<input type="hidden" name="action" value="preselected_device" />
				<button type="submit" style="background: none; color: inherit; border: none; padding: 0; font: inherit; cursor: pointer; outline: inherit;">
					<div class="small-card radio">
						<img src="{{ url_for('static', filename='img/key.svg') }}" class="svg-white" style="width: 120px;">
						{{ _("Create single key wallet") }}
					</div>
				</button>
			</form>
			{% if specter.device_manager.devices | length > 1 %}
				<a href="{{ url_for('wallets_endpoint.new_wallet', wallet_type='multisig') }}" style="text-decoration: none;">
					<div class="small-card radio">
						<img src="{{ url_for('static', filename='img/two-keys.svg') }}" class="svg-white" style="width: 120px;">
						{{ _("Create multisignature wallet") }}
					</div>
				</a>
			{% endif %}
		</div>
	</div>
{% endblock %}

{% block scripts %}
	<script>
		document.addEventListener("DOMContentLoaded", function() {
			var deviceType = document.getElementById("device_type");
			if (deviceType != null) {
				deviceType.value = '{{ device.device_type }}';
			}
			deviceType.addEventListener("change", function() {
				var setTypeButton = document.getElementById("settype");
				if (deviceType.value != '{{ device.device_type }}') {
					setTypeButton.style.display = 'block';
				} else {
                	setTypeButton.style.display = 'none';
				}
			}, false);

			var isNewDevice = location.search.split('newdevice=')[1]
			if (isNewDevice) {
				showPageOverlay('new_device_popup');
			}

			// Prefill address and derivation path when coming from an individual address
			let origin = "{{ origin }}"
			let address = "{{ address }}"
			let derivation_path = "{{ derivation_path }}"
			if (origin == "wallet") {
				document.getElementById('signing-address').value = address
				document.getElementById('messageDerivationPath').value = derivation_path
				showPageOverlay('message-signing')
			} 

			// Event listener for sign message via QR code-button 
			{% if device.device_type == "specter" %}
			document.getElementById("{{ device.alias }}_qr_sign_msg_btn").addEventListener("click", e => {
                    e.preventDefault();
                    hidePageOverlay();
                    // This makes qr_code_sign_message.jinja visible
                    showPageOverlay('{{ device.alias }}_sign_msg_qr');
                    // This set the qr-code web component in qr_code_sign_message.jinja
                    QRcodeSetter();
                });
			{% endif %}
		});

		async function signMessageOnDevice() {
			hidePageOverlay();
			let signature = await signMessage(
				'{{ device.device_type }}',
				document.getElementById('message').value,
				document.getElementById('messageDerivationPath').value
			);
			if (signature) {
				document.getElementById('signature-label').style.display = 'block';
				let signatureElement = document.getElementById('signature');
				signatureElement.classList.remove("hidden")
				signatureElement.classList.add("signature")
				signatureElement.innerText = signature;
				document.getElementById('{{ device.alias }}_usb_sign_msg_btn').remove()
				showPageOverlay('message-signing');
				showNotification(`{{ _("Message was signed successfully!") }}`)
			}
			else if (signature === undefined) {
				showError(`{{ _("No signature received from the device. Did you cancel the signing?") }}`, 3000)
			}
			else {
				showError(`{{ _("Message signing failed.") }}`, 3000)
			}
		}

		function QRcodeSetter() {
			let messageText = document.getElementById('message').value
			let derivationPath = document.getElementById('messageDerivationPath').value
			// This QR code only works for the DIY
			fullStringToEncode = `signmessage ${derivationPath} ascii:${messageText}`
			document.getElementById('msg-qr-code').setAttribute("value", fullStringToEncode)
		}
	</script>
{% endblock %}
