{% extends "base.jinja" %}

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

	{% if device %}
		<h1>{{ _("Adding keys to") }} {{ device.name }}</h1>
	{% else %}
		<h1>{{ _("Setting up a new device") }}</h1>
	{% endif %}

	<div>
		<form action="./" method="POST" onsubmit="{% if not device %}return checkType();{% endif %}">
			<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>

			{% if not device %}
				<div class="space-y-3 mt-5">
					<div class="floating-wrapper">
						<input class="floating-input peer" placeholder=" " type="text" id="device_name" name="device_name" value="{{ device_name }}">
						<label class="floating-label" for="device_name">{{ _("Name Your Device") }}</label>
					</div>
					{% include "device/components/device_type.jinja" %}

					<p class="warning hidden" id="type_reminder"><img src="{{ url_for('static', filename='img/info_sign.svg') }}" data-style="width: 20px;"/>{{ _("Please make sure to choose the device type before continuing") }}</p>

					<div id="toggle_passphrase_container" class="hidden">
						<p>{{ _("Device Management") }}</p>
						<div>
							<button type="button" class="button" onclick="togglePassphrase(document.getElementById('device_type').value)">{{ _("Toggle device passphrase") }}</button>
						</div>
					</div>
				</div>
			{% endif %}

			{% if not device or not device.hot_wallet %}
				<div id="cold_device" class="mt-10 flex flex-col">
					<h2>{{ _("Scan, paste or load xpubs") }}</h2>

					{% if not device %}
						<p>
							{{ _("You will be able add more keys later from the device menu.") }}
						</p>
					{% endif %}

					<p>{{ _("One line per xpub. Ideally with derivation path in the form") }}: <span data-style="font-style: italic; font-weight: bold; font-size: 15px;">[ fingerprint / derivation / path ] xpub.</span></p>

					<textarea id="txt" name="xpubs" placeholder='{{ _("Enter your xpubs here") }}'>{{ xpubs }}</textarea>

					<p class="mt-3 mb-0 selection-button cursor-pointer" data-style="text-decoration: underline; cursor: pointer;" onclick="showPageOverlay('usb_import_account_number')">{{ _("Specify account number (advanced)") }}</p>

					<div class="flex space-x-3 mt-3">
						<qr-scanner id="xpub-scan">
							<a slot="button" href="#" class="button mb-3">
								<img src="{{ url_for('static', filename='img/qr-code.svg') }}" data-style="width: 26px; margin-right: 2px;" class="svg-white"> {{ _("Scan QR Code") }}
								<tool-tip width="200px">
											<h4 slot="title">{{ _("Using an airgapped device with QR codes") }}</h4>
											<span slot="paragraph">
												{{ _("Scan QR codes with extended public keys one by one.") }}
												{{ _("We recommend importing ")}}<b>{{ _('Native Segwit')}}</b>{{ _(' and ')}}<b>{{ _('Segwit Multisig')}}</b>{{ _(' keys.')}}
											</span>
									</tool-tip>
							</a>
						</qr-scanner>

						<div>
							<input type="file" id="file" class="inputfile hidden" multiple/>
							<label for="file" class="button mb-3" data-style="margin: 8px;">
								<img src="{{ url_for('static', filename='img/file.svg') }}" data-style="width: 26px; margin-right: 2px;" class="svg-white">
								{{ _("Choose files") }}
								<tool-tip width="200px">
											<h4 slot="title">{{ _("Using an airgapped ColdCard with MicroSD") }}</h4>
											<span slot="paragraph">
										{{ _("Export extended public keys for single-key wallets to the SD card from") }}
										<b>Advanced → MicroSD → Export Wallet → Generic JSON</b>
										{{ _("To export multisignature pubkeys go to") }}
										<b>Settings → Multisig Wallets → Export XPUB</b>
										{{ _("We recommend using Native Segwit.") }}
											</span>
								</tool-tip>
							</label>
						</div>
					</div>

					<div class="flex">
						<button type="button" class="button" data-style="margin: 8px;" id="askhwi">
							<img src="{{ url_for('static', filename='img/usb.svg') }}" data-style="width: 26px; margin-right: 2px;" class="svg-white"> {{ _("Get via USB") }}
						</button>
					</div>


					<div class="hidden p-4 bg-dark-800 w-96" id="usb_import_account_number">
						<div class="flex justify-between mb-3">
								<h3 class="mb-0">{{ _("Select Account") }}</h3>
								<p class="m-0 cursor-pointer" onclick="hidePageOverlay()" class="cursor-pointer">Close</p>
						</div>
						<p>{{ _("You can set which account number you wish to import. ")}}{{ _("Account derivation uses the number choosen here to derive an xpub as specified in") }} <a data-style="color: #fff" href="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#account" target="_blank">BIP44</a>.</p>
						<p>{{ _("This is an advanced feature.")}}{{ _(" If you're not familiar with account derivations please leave this as 0.") }}</p>
						<div class="floating-wrapper mb-5 mt-3">
							<input class="floating-input peer" placeholder=" " type="number" step="1" min="0" value="0" id="usb_account_number">
							<label class="floating-label">Account Number</label>
						</div>
						<button class="button text-white bg-accent" type="button" onclick="hidePageOverlay()">{{ _("Complete") }}</button>
					</div>

					<div class="mb-5">
						{{ _("Examples") }}:
						<pre data-style="font-size: 1em">
[f79ec910/84'/1'/0']tpubDA5h1hw24fzoBi9...pR1DiM4EBu
[F79EC910/48h/1h/0h/2h]Vpub5DRk6RvRAjZf9rmZV1Q8...TZSDQL67e5i
upub5En4f7k8gaG2KDHvBeEYox...rFpJRHpiZ4DE
						</pre>
					</div>

					<button type="submit" class="button bg-accent text-white self-end" name="action" value="newcolddevice" onsubmit="showPacman()">{{ _("Continue") }}</button>
				</div>

			{% endif %}
{% if not device or device.hot_wallet %}
			<div id="hot_device" class="hidden">
				<p class="note" data-style="border-radius: 5px; padding: 20px; background: rgba(0,0,0,0.1); color: #ccc;">
					<span data-style="display: inline-block;font-weight: bold; margin-bottom: 8px;">⚠️ {{ _("A note on hot wallets") }}:</span>
					{{ _('This will create a ')}}<a data-style="color: #ddd;" href="https://en.bitcoin.it/wiki/Hot_wallet" target="_blank">{{ _('hot wallet')}}</a>{{ _(' on your Bitcoin Core node.')}}
					{{ _("Hot wallets are considered less secure and are not recommended for use with significant amounts. Use with caution and beware the potential risks.") }}
				</p>
				<p>{{ _("Enter you mnemonic here or use the randomly generated one") }}:</p>
				<p><b>{{ _("Make sure to backup these words!") }}</b></p>
				{% set wordslist = mnemonic.split(' ') %}
				<nav class="row">
					<button type="button" id="generate_mnemonic_btn" class="button radio left checked" onclick="setMnemonicView('generate')"> {{ _("Generate") }} </button>
					<button type="button" id="import_mnemonic_btn" class="button radio right" onclick="setMnemonicView('import')"> {{ _("Import") }} </button>
				</nav>
				<input id="mnemonic_value" type="hidden" name="mnemonic" value="{{ mnemonic }}"/>
				<textarea id="import_mnemonic" class="hidden" id="txt" placeholder='{{ _("Enter your mnemonic here (English, Spanish and Italian are supported)") }}'></textarea>
				<div id="generated_mnemonic">
					<div id="generated_mnemonic_row" class="row center break-row-mobile" data-style="max-height: 30px;">
						<fieldset data-style="border:none; display: inline;"> 
							<select name="strength" id="strength">
								<option value="128">12 words</option>
								<option value="256">24 words</option>
							</select>
						</fieldset>
						<button type="submit" class="button" name="action" value="generatemnemonic" data-style="margin: auto;max-width: 200px;">{{ _("Generate New Mnemonic") }}</button>
					</div>
					<table>
						{% for i in range(wordslist|length // 4) %}
							<tr>
								<td>{{ 4 * i + 1 }} {{ wordslist[4 * i] }}</td>
								<td>{{ 4 * i + 2 }} {{ wordslist[4 * i + 1] }}</td>
								<td>{{ 4 * i + 3 }} {{ wordslist[4 * i + 2] }}</td>
								<td>{{ 4 * i + 4 }} {{ wordslist[4 * i + 3] }}</td>
							</tr>
						{% endfor %}
					</table>
				</div>
				<label>{{ _("Encrypt Wallet File") }}: </label>
				<input type="password" name="file_password" class="inline" placeholder="password">
				<span id="toggle_advanced" data-style="cursor: pointer;">{{ _("Advanced") }} &#9654;</span>
				<div id="advanced_settings" class="hidden">
					<label>{{ _("BIP39 passphrase (optional)") }}: </label>
					<input type="password" name="passphrase" class="inline" placeholder="passphrase">
					<p>{{ _("Derivation paths") }}:
					<span class="note">
					{{ _("Enter each derivation path as a separate line. Start each path with an ")}}<code>m</code>{{ _('. No trailing slash.')}}</span>
					</p>
					<textarea name="derivation_paths" placeholder='{{ _("Specify derivation paths to import for the wallet") }}'>
m/84h/{{ 0 if specter.info.chain == "main" else 1 }}h/0h
m/49h/{{ 0 if specter.info.chain == "main" else 1 }}h/0h
m/48h/{{ 0 if specter.info.chain == "main" else 1 }}h/0h/1h
m/48h/{{ 0 if specter.info.chain == "main" else 1 }}h/0h/2h</textarea>
				<p data-style="margin-bottom: 10px;">{{ _("Address range to import") }}: </p>
				{{ _("From") }}: <input type="number" name="range_start" class="inline" placeholder="start" value=0 step=1 min=0 max=100000>
				<br class="mobile-only">
				<br class="mobile-only">
				{{ _("to") }}: <input type="number" name="range_end" class="inline" placeholder="start" value=1000 step=1 min=0 max=100000>
				</div>
				<button type="submit" class="button centered" name="action" value="newhotdevice">{{ _("Continue") }}</button>
			</div>
{% endif %}
		</form>
	</div>

{% endblock %}
{% block scripts %}
<script type="text/javascript">
	function toggleAdvanced() {
		let advancedButton = document.getElementById('toggle_advanced');
		let advancedSettings = document.getElementById('advanced_settings');
		if (advancedSettings.style.display === 'block') {
			advancedSettings.style.display = 'none';
			advancedButton.innerHTML = `{{ _("Advanced") }} &#9654;`;
			if (isCoinSelectionActive()) {
				toggleExpand();
			}
		} else {
			advancedSettings.style.display = 'block';
			advancedButton.innerHTML = `{{ _("Advanced") }} &#9660;`;
		}
	}

	function setMnemonicView(view) {
		var generatedMnemonic = document.getElementById("generated_mnemonic");
		var importMnemonic = document.getElementById("import_mnemonic");
		var generateMnemonicBtn = document.getElementById("generate_mnemonic_btn");
		var importMnemonicBtn = document.getElementById("import_mnemonic_btn");
		var mnemonicValue = document.getElementById("mnemonic_value");
		if (view == 'generate') {
			generatedMnemonic.style.display = 'block';
			importMnemonic.style.display = 'none';
			generateMnemonicBtn.className = generateMnemonicBtn.className += ' checked';
			importMnemonicBtn.className = importMnemonicBtn.className.replace(/checked/, '');
			mnemonicValue.value = `{{ mnemonic }}`
		} else {
			generatedMnemonic.style.display = 'none';
			importMnemonic.style.display = 'block';
			generateMnemonicBtn.className = generateMnemonicBtn.className.replace(/checked/, '');
			importMnemonicBtn.className = importMnemonicBtn.className += ' checked';
			mnemonicValue.value = importMnemonic.value;
			importMnemonic.addEventListener("input", function() {
				mnemonicValue.value = importMnemonic.value;
			});
		}
	}
	const deviceType = document.getElementById("device_type");
	function checkType() {
		if (!deviceType.value) {
			type_reminder.style.display = 'block';
		} else {
			type_reminder.style.display = 'none';
			if(deviceType.value == 'bitcoincore'){
				showPacman();
			}
			return true;
		}
		return false;
	}

	document.addEventListener("DOMContentLoaded", function(){
		function setPubkeysView() {
			var coldDevice = document.getElementById("cold_device");
			var hotDevice = document.getElementById("hot_device");
			if (deviceType.value == 'bitcoincore' || deviceType.value == 'bitcoincore_watchonly') {
				coldDevice.style.display = 'none';
				hotDevice.style.display = 'flex';
			} else {
				coldDevice.style.display = 'flex';
				hotDevice.style.display = 'none';
			}
			{% for cls in specter.device_manager.supported_devices %}
            	if (deviceType.value == '{{ cls.device_type }}') {
					if ('{{ cls.supports_hwi_toggle_passphrase }}' === 'True') {
						document.getElementById('toggle_passphrase_container').style.display = 'block';
					} else {
						document.getElementById('toggle_passphrase_container').style.display = 'none';
					}
				}
            {% endfor %}
			
		}
		var typeReminder = document.getElementById("type_reminder");

		if(deviceType!=null){
			deviceType.addEventListener("change", function() {
				type_reminder.style.display = 'none';
				setPubkeysView();
			}, false);
			deviceType.value = '{{ device_type }}';
			setPubkeysView();
		}

		var strength = document.getElementById("strength");
		if(strength!=null){
			strength.value = '{{ strength }}';
		}
		document.getElementById('toggle_advanced').addEventListener('click', (event) => {
			toggleAdvanced();
		});
		if ('{{ device and device.hot_wallet }}' == 'True') {
			setMnemonicView('import');
			var hotDevice = document.getElementById("hot_device");
			hotDevice.style.display = 'block';
		}
	});
</script>

{% if not device or not device.hot_wallet %}
<script type="text/javascript">
	{% include "device/components/add_keys.js" %}

	document.getElementById('askhwi').addEventListener('click', async e=>{
		// Ensure that device type was selected
		if (!checkType()) {
			return
		}
		// detect devices
		let devices = await enumerate(deviceType.value);
		if(devices == null){
			return
		}
		// this shouldn't happen actually
		if(devices.length == 0){
			showError(`{{ _("No devices found") }} :(`);
			return;
		}
		console.log(devices)
		// first only for now
		let device = await selectDevice(devices);
		console.log(device);
		// nothing to do if user cancelled
		if(device == null){
			return;
		}
		
		let account = document.getElementById('usb_account_number').value;
		let xpubs = await getXpubs(device, account, "", "{specter.chain}");
		if(xpubs == null){
			return;
		}
	    addKeys(xpubs);
	    setDeviceType(device.type);
	});

</script>
{% endif %}
<script type="text/javascript">

	document.addEventListener("DOMContentLoaded", function(){
		var el = document.getElementById("file");
		var txt = document.getElementById("txt");

		if (el != null) {
			el.addEventListener("change", (e) => {
				files = e.currentTarget.files;
				console.log(files);
				for(let i=0; i<files.length; i++){
					console.log(files[i].name);
					let reader = new FileReader();
					reader.onload = function(e) {
						let str = reader.result
						let data = "";
						if (str.indexOf("{") >= 0) {
							let json = JSON.parse(str);
							console.log(str);
							if ("keystore" in json) { // ColdCard electrum file
								let prefix = "";
								let fingerprint = "";
								if ("ckcc_xfp" in json.keystore){
									let num = json.keystore.ckcc_xfp;
									for (let i = 0; i < 4; i++) {
										fingerprint += ('0' + (num % 256).toString(16)).slice(-2);
										num = num >>> 8;
									}
								}
								if ("root_fingerprint" in json.keystore){
									fingerprint = json.keystore.root_fingerprint;
								}
								if ((fingerprint.length > 0) && ("derivation" in json.keystore)) {
									prefix = "[";
									prefix += fingerprint;
									prefix += json.keystore.derivation.substring(1).replace(/'/g,"h");
									prefix += "]";
								}
								let s = prefix + json.keystore.xpub + "\n";
								data += s;
							} else if (("bip84" in json) && ("xfp" in json)){
							// coldcard generic file
								let s = "";
								["bip44","bip49","bip84"].forEach((bip)=>{
									if(bip in json){
										let der = json[bip].deriv.replace("m","").replace(/'/g,"h");
										let xpub = json[bip].xpub;
										if("_pub" in json[bip]){
											xpub = json[bip]["_pub"];
										}
										s += `[${json.xfp}${der}]${xpub}\n`;
									}
								});
								data += s;
							} else if ("xfp" in json) {
							// probably ColdCard multisig file
								let s = "";
								for (let k in json) {
									if (k+"_deriv" in json) {
										s += "["+json.xfp+json[k+"_deriv"].substring(1)+"]"+json[k]+"\n";
									}
								}
								data += s;
							}
						} else {
							str.split("\n").forEach((line)=>{
								if(line.indexOf("(") >= 0){
									let arr = line.split("(");
									let args = arr[arr.length-1].split(")")[0];
									// if multisig
									args.split(",").forEach((arg) => {
										// must have pub in xpub
										if(arg.indexOf("pub") > 0){
											let re = /(.*pub[^/]*).*/g.exec(arg);
											if(re){
												data += re[re.length-1].replaceAll("'","h") + "\n";
											}
										}
									});
								}else{
									data += line+"\n";
								}
							});
						}
						addKeys(data);
						setDeviceType('coldcard');
					}
					reader.readAsText(files[i]);
				}
			});
		}
	});
</script>

<script type="text/javascript">
	let scanner = document.getElementById('xpub-scan');
	if(scanner != null) {
		scanner.addEventListener('scan', e=>{
			let result = e.detail.result;
			if(result==null){
				return;
			}
			let deviceType = document.getElementById("device_type");
			// cobo uses json format
			if(result.includes("{")){
				let obj = JSON.parse(result);
				if( ("ExtPubKey" in obj) && 
					("AccountKeyPath" in obj) && 
					("MasterFingerprint" in obj)){
					console.log(obj);
					let path = obj.AccountKeyPath.replace(/'/g,'h');
					let str = `[${obj.MasterFingerprint}/${path}]${obj.ExtPubKey}`;
					addKeys(str);
					setDeviceType('cobo');
				}else if( ("xfp" in obj) &&
						  ("xpub" in obj) &&
						  ("path" in obj)){
					console.log(obj);
					let path = obj.path.replace(/'/g,'h').replace("m/","");
					let str = `[${obj.xfp}/${path}]${obj.xpub}`;
					addKeys(str);
					setDeviceType('cobo');
				}else{
					showError(`{{ _("Unknown key format") }}`);
				}
			}else{
				addKeys(result);
				setDeviceType('specter');
			}
		});
	}
</script>

{% endblock %}
