{% extends "base.jinja" %}
{% block main %}
	{% include "includes/overlay/key_export_qr.jinja" %}
	{% include "includes/hwi/hwi.jinja" %}
	{% include "includes/qr-scanner.html" %}

	<h1 id="title">{{ device.name }}</h1>

	{% from 'components/editable_title.jinja' import editable_title %}
	{{ editable_title(device.name) }}

	<div class="table-holder my-10">
		<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 table-key">{{ _("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') }}">
								<img src="{{ url_for('static', filename='img/qr-code.svg') }}"/>
							</td>
						{% endif %}
						<td class="xpub scroll optional">
							<div class="table-key">
								{% if specter.hide_sensitive_info %}
									<span class="explorer-link">##################################################</span>
								{% else %}
									<span class="explorer-link" onclick="copyText('{{ key }}', 'Copied key: {{ key }}')">{{ key }}</span>
								{% endif %}
							</div>
						</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 bg-dark-600 w-20">{{ _("Delete") }}</button>
							</form>
						</td>
					</tr>
				{% endfor %}
			</tbody>
		</table>
	</div>

	<div>
		<form action="./" method="POST">
			<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
			<div class="flex mb-5 w-[344px]">
				{% include "device/components/device_type.jinja" %}
			</div>
			<button type="submit" class="button text-white bg-accent mt-3 hidden" id="settype" name="action" value="settype">{{ _("Update") }}</button>
		</form>

		<form action="./" method="POST">
			<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
			{% if device.device_type != "bitcoincore_watchonly"%}
				<button class="button" id="add_keys" type="submit" name="action" value="add_keys">{{ _("Add more keys") }}</button>
			{% else %}
				<button class="button"  id="add_keys" type="submit" name="action" value="add_keys">{{ _("Convert to hot wallet") }}</button>
			{% endif %}
		</form>

		{% if device.hwi_support or device.supports_qr_message_signing %}
		<button class="button" type="button" onclick="showPageOverlay('message-signing')">{{ _("Sign message") }}</button>

		<div id="message-signing" class="hidden p-4 bg-dark-800">
			<div class="flex justify-between mb-3">
					<h3 class="mb-0">{{ _("Message Signing") }}</h3>
					<p class="m-0 cursor-pointer" onclick="hidePageOverlay()" class="cursor-pointer" data-cy="close-msg-signing-overlay-btn">Close</p>
			</div>
			{% if origin %}
				<div class="floating-wrapper">
					<input class="floating-input peer" type="text" id="signing-address" type="text" value="" placeholder=" ">
					<label for="signing-address" class="floating-label">Address</label>
				</div>
			{% endif %}

			<div class="floating-wrapper">
				<input class="floating-input peer" type="text" id="messageDerivationPath" type="text" value="" placeholder=" ">
				<label class="floating-label">{{ _("Derivation path (e.g. m/84h/0h/0h/0/0)") }}</label>
			</div>

			<textarea class="my-3" id="message" placeholder="Enter the message you would like to sign"></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 class="button mb-0 bg-accent" id="{{ device.alias }}_usb_sign_msg_btn" type="button" onclick="signMessageOnDevice();">{{ _("Sign message via USB") }}</button>
			{% endif %}

			{% if device.supports_qr_message_signing %}
				{% include "includes/overlay/qr_code_sign_message.jinja" %}
				<button class="button mb-0 mt-3 bg-accent" id="{{ device.alias }}_qr_sign_msg_btn">{{ _("Sign message via QR code") }}</button>
			{% endif %}

		</div>
		{% endif %}

		{% if specter.is_liquid %}
			<br>
			<a class="button" 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 class="button" type="button" 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 class="button" type="submit" name="action" value="forget" id="forget_device">{{ _("Forget the device") }}</button>
		</form>
	</div>

	{% if wallets %}
	<div class="mt-20">
		<h2>{{ _("Wallets Using This Device") }}</h2>
		<div class="grid grid-cols-4 gap-5">
			{% for wallet in wallets %}
				<a href="{{ url_for('wallets_endpoint.wallet', wallet_alias=wallet.alias) }}" >
					<div class="selection">
						<p> </p>
						<img src="{{ url_for('static', filename='img/' + ('two-keys' if wallet.is_multisig else 'key') + '.svg') }}">
						<p>{{ wallet.name }}</p>
					</div>
				</a>
			{% endfor %}
		</div>
	</div>
	{% endif %}

	<div class="hidden bg-dark-900 p-4 pb-6" id="new_device_popup">
    <div class="flex justify-between mb-5">
        <h3 class="mb-0">{{ _("Device Added") }}</h3>
        <p class="m-0 cursor-pointer" onclick="hidePageOverlay()" class="cursor-pointer" data-cy="new-device-added-screen-close-btn">Close</p>
    </div>
		<div class="grid grid-cols-2 gap-3">
			<form class="text-[0px]" 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">
					<div class="selection">
						<p></p>
						<img src="{{ url_for('static', filename='img/key.svg') }}">
						<p>{{ _("Create single key wallet") }}</p>
					</div>
				</button>
			</form>
			{% if specter.device_manager.devices | length > 1 %}
				<a href="{{ url_for('wallets_endpoint.new_wallet', wallet_type='multisig') }}">
					<div class="selection">
						<p></p>
						<img src="{{ url_for('static', filename='img/two-keys.svg') }}">
						<p>{{ _("Create multisignature wallet") }}</p>
					</div>
				</a>
			{% endif %}
			<a href="{{ url_for('devices_endpoint.new_device_type') }}">
				<div class="selection">
					<p></p>
					<img src="{{ url_for('static', filename='img/plus.svg') }}">
					<p>{{ _("Add another device") }}</p>
				</div>
			</a>
		</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.supports_qr_message_signing %}
				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 %}
