{% extends "wallet/components/wallet_tab.jinja" %}
{% set tab = 'send' %}
{% block content %}

	<style> 
		#calculated_tx_fee_label:hover {
			text-decoration: underline;
			cursor: pointer;
		}
	</style>

	{% include "includes/qr-scanner.html" %}
	{% include "includes/recipient-box.html" %}

	{% from 'wallet/send/components/send_nav.jinja' import send_nav %}
	{{ send_nav('send_new', wallet_alias) }}

	<message-box type="error" id="amount_errors_container" style="position: absolute; top: 0; display: none;">
		Error!
		</ul>
	</message-box>

	<form action="{{ url_for('wallets_endpoint.send_new',wallet_alias=wallet_alias) }}" id="send-form" method="POST" style="width: 100%;">
		<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
		<input type="hidden" name="rbf_tx_id" value="{{ rbf_tx_id }}"/>
		<input type="hidden" name="recipient_dicts"  id="recipient_dicts" value=""/>  
		<h1 class="padded">{{ _("Create Transaction") }}</h1>
		<div style="display: flex; justify-content: center; margin-bottom: 15px">
			<div>{{ _("Available funds:") }} {{wallet.amount_available | btcunitamount}}
				{% if specter.unit == 'sat' %}
					sats
				{% else %}
					{% if specter.is_testnet %}t{%endif%}{% if specter.is_liquid %}L{%endif%}BTC
				{% endif %}<br>
				{% if specter.price_check %}
					<span class="note">{{ wallet.amount_available | altunit }}</span>
				{% endif %}
				{% if specter.is_liquid and wallet.balance.get("assets", {}) %}
				<span>
					<br>{{ _("Assets:") }}<br>
					{% for asset in wallet.balance.get("assets",{}).keys() | sort %}
						{% set balance = wallet.balance.get("assets",{}).get(asset, {}) %}
						<span style="margin: 0 10px;">
							{{ (balance.get("trusted", 0) + balance.get("untrusted_pending", 0) + balance.get("immature", 0)) | btcamount }}
							<asset-label data-asset="{{asset}}" data-label="{{asset | assetlabel}}"></asset-label>
						</span>
					{% endfor %}
				</span>
				{% endif %}
			</div>
			{% if wallet.amount_locked_unsigned  > 0 or wallet.amount_frozen > 0 %}
			<div>
				<tool-tip width="150px">
				    <h4 slot="title">{{ _("Why is this less than my total balance?") }}</h4>
				    <span slot="paragraph">
						{{ _(' Frozen outputs and outputs locked in unsigned transactions are not available here.  
						To make more funds available, click on the "Unsigned" tab and delete not required transactions or unfreeze UTXO under "Transactions".') }}
				    </span>
				</tool-tip>
	        </div>
	        {% endif %}
	    </div>
		<div class="card" style="margin: auto;">			
			<div id="recipients" {% if ui_option != 'ui' %}class="hidden"{% else %} class="recipient_wrapper" {% endif %}></div>
			<img src="{{ url_for('static', filename='img/add-person.svg') }}" id="add-recipient" title="Add a recipient" class="recipient_button recipient_add" style="float:right" onclick="addRecipient('', '', 'btc', '')">
			<div id="recipients-txt-container" {% if ui_option == 'ui' %}class="hidden"{% endif %}>
			{{ _("Unit:") }} 
			<label><input type="radio" class="inline" style="margin: 0 5px;" name="amount_unit_text" value="sat" onchange="toggleTextUnit(this)" {% if specter.unit == 'sat' %}checked{% endif %}>sat</label>
			<label><input type="radio" class="inline" style="margin: 0 5px;" name="amount_unit_text" value="btc" onchange="toggleTextUnit(this)" {% if specter.unit != 'sat' %}checked{% endif %}>BTC</label><br>

			<textarea id="recipients-txt" name="recipients" placeholder="{{ _('Enter recipient address, amount') }}" style="margin-top: 5px; font-size: 0.95em;" onblur="validateForm()">{{ recipients_txt }}</textarea>
				<p class="note" style="line-height: 2; background-color: #16202d; padding: 10px; border-radius: 7px;">
					{{ _("Enter each recipient address, amount as a new line:") }}<br>
					&lt;{{ _("ADDRESS") }}1&gt;, &lt;{{ _("AMOUNT") }}1&gt;<br>
					&lt;{{ _("ADDRESS") }}2&gt;, &lt;{{ _("AMOUNT") }}2&gt;<br>
					&lt;{{ _("ADDRESS") }}3&gt;, &lt;{{ _("AMOUNT") }}3&gt;<br>
				</p>
			</div>
			<p><span id="calculated_tx_fee_label" class="note" style="margin-top: 17px;" onclick="calculateEstimatedFee()">{{ _("Calculate estimated fee") }}</span><span class="note" id="calculated_tx_fee"></span><p>
			<span id="toggle_advanced" style="cursor: pointer;">{{ _("Advanced") }} {% if show_advanced_settings %}&#9660;{% else %}&#9654;{% endif %}</span>
			<br>
			<div id="advanced_settings" style="margin: auto; max-width: 90%; display: {% if show_advanced_settings %}block{% else %}none{% endif %};">
				<div>{{ _("Transaction editor:") }} 
					<label><input type="radio" class="inline" style="margin: 0 10px 0 20px;" name="ui_option" value="ui" onclick="toggleSendUIType(this)" {% if ui_option == 'ui' %}checked{% endif %} id="ui-radio-btn">UI</label>
					<label><input type="radio" class="inline" style="margin: 0 10px 0 20px;" name="ui_option" value="text" onclick="toggleSendUIType(this);" {% if ui_option != 'ui' %}checked{% endif %}>text</label>
				</div><br>
				{% include "includes/fee-selection.html" %}
				<fee-selection id="fee-selection-component"></fee-selection>
				<br>
				<br>
				<br>
				<div class="row break-row-mobile" id="vertical-space-for-subtract-fees-from-amount-checkbox" style="margin-top: 0px;"></div>
			</div>
			{% include "includes/tx-row.html" %}
			{% include "includes/tx-data.html" %}
			{% include "includes/explorer-link.html" %}
			{% include "includes/tx-table.html" %}
			{% include "includes/coin_selection.html" %}
			<coin-selection  
				id="coinselection-webcomponent"
				wallet-alias="{{wallet.alias}}"
				spendable-amount='{{ wallet.full_available_balance | btcamount }}'
				is-liquid="{{specter.is_liquid}}"
				selected-coins="{{ selected_coins }}">
			</coin-selection>
			<button onclick="validateForm(true)" type="button" name="action" value="createpsbt" id="create_psbt_btn" class="btn centered" style="margin-top: 20px;">{{ _('Create ')}}<span class="optional">&nbsp;{{ _('unsigned')}}&nbsp;</span>{{ _('transaction') }}</button>
		</div>
	</form>
{% endblock %}

{% block scripts %}
	<script>
		{% if specter.is_liquid %}
			const MIN_FEE_RATE = 0.1;
			const NETWORK = "Liquid"
		{% else %}
			const MIN_FEE_RATE = 1;
			const NETWORK = "Bitcoin"
		{% endif %}

		function getRecipientIds() {
			var ids = [];
			var children = document.getElementById(`recipients`).children;
			for (var i = 0; i < children.length; i++) {
				ids.push(children[i].recipientId)
			}
			return ids
		}

		// combines all html recipients to a list
		function getRecipients() {
			var data = [];

			var recipientIds = getRecipientIds();
			for  (var i in recipientIds)   {
				var recipientId = recipientIds[i];
				let recipient = document.getElementById(`recipient_${recipientId}`);
				data.push(recipient);
			}

			return data;
		}


		// combines all recipient.value's to a list
		function getRecipientDicts() {
			var data = [];

			var recipients = getRecipients();
			for  (var i in recipients)   {
				data.push(recipients[i].value);
			}

			return data;
		}

		function setVisibilityRemoveRecipientButton(){
			var recipientList = getRecipients();
			var hidden = recipientList.length == 1
			for (var i in recipientList) {
				recipientList[i].hiddenRemoveButton = hidden;
			}	

		}

		// Amounts and units
		var textUnit = '{{ specter.unit }}';
		// TODO: use total balance including unconfirmed
		var assetBalances = {
			"btc": {
				"balance": {{ wallet.full_available_balance }},
				"label": "{% if specter.is_testnet %}t{%endif%}{% if specter.is_liquid %}L{%endif%}BTC",
			},
			"sat": {
				"balance": Math.round({{ wallet.full_available_balance*1e8 }}),
				"label": "sat",
			},
		{% for asset in wallet.balance.get("assets",{}).keys() | sort %}
			"{{asset}}": {
				"balance": {{wallet.balance.get("assets",{}).get(asset, {}).get("trusted", 0)}},
				"label": "{{ asset | assetlabel }}",
			},
		{% endfor %}
		};
		var spendableAmount = {{ wallet.full_available_balance }}

		// Set up web components
		var coinselectionWebcomponent = document.getElementById('coinselection-webcomponent');
		coinselectionWebcomponent.assetBalances = assetBalances
		coinselectionWebcomponent.addEventListener("change", (event) => {
			validateForm()
		})
		var FeeSelectionComponent = document.getElementById('fee-selection-component')
		FeeSelectionComponent = document.getElementById('fee-selection-component')

		// Switch off RBF and subtract fee for Liquid
		function adjustForLiquid() {
			if (NETWORK == "Liquid") {
			console.log("On Liquid, removing RBF and subtract from features ... ")
			FeeSelectionComponent.deactivateRbf()
			FeeSelectionComponent.deactivateSubtract() // Subtract from is still set to true for send max under the hood
			// Remove some line breaks
			advancedSettingsDiv = document.getElementById("advanced_settings")
			lineBreaks = Array.from(advancedSettingsDiv.querySelectorAll('br'))
			lineBreaks.pop() // We still need the last line break
			for (var br of lineBreaks) {
				if (br.parentNode == advancedSettingsDiv) {
					advancedSettingsDiv.removeChild(br)
				}
			}
			}	
		}
		
		// Main part of displaying subtractFrom, the rest is with addRecipient, deleteRecipient and toggleSendUIType
		FeeSelectionComponent.addEventListener("subtractClick", (event) => {
			if ((getRecipientIds().length > 1 || !document.getElementById('ui-radio-btn').checked) && document.getElementById('subtract').checked) {
				FeeSelectionComponent.showSubtractFrom(true)
				if (!document.getElementById('ui-radio-btn').checked) {
					FeeSelectionComponent.addLineBreaks(2)
				}
			} 
			else {
				FeeSelectionComponent.showSubtractFrom(false)
				if (!document.getElementById('ui-radio-btn').checked) {
					FeeSelectionComponent.removeLineBreaks()
				}
			}
		})


		function addRecipient(address, amount, amount_unit, label) {
			let recipientIds = getRecipientIds();
			recipientId = 0;
			if (recipientIds.length > 0) {
				recipientId = Math.max(...recipientIds)+1
			}; 

			// This adds the recipient
			let recipients = document.getElementById('recipients');			
			let newRecipient = new RecipientBox();
			newRecipient.id = `recipient_${recipientId}`;
			newRecipient.recipientId = recipientId;
			newRecipient.title = `Recipient ${recipientId+1}`;
			newRecipient.address = address;
			newRecipient.amount = amount;
			newRecipient.unit = amount_unit;
			newRecipient.label = label;
			newRecipient.addEventListener('remove', (event) => {
				removeRecipient(newRecipient.recipientId);
			})
			newRecipient.addEventListener('address-input', (event) => {
				validateForm();
			})
			newRecipient.addEventListener('unit-change', (event) => {
				validateForm();
			})
			newRecipient.addEventListener('send-max', (event) => {
				setMaxAmount(newRecipient.recipientId);
			})

				


			recipients.appendChild(newRecipient);

			// This adds the id's to the subtract_from_recipient_id_select
			var feeSelectionComponent = document.getElementById('fee-selection-component');
			var subtractFromRecipientIdSelect = feeSelectionComponent.subtractFrom.children.subtract_from_recipient_id_select;
			var opt = document.createElement('option');
			opt.value = recipientId;
			opt.innerHTML = newRecipient.title;
			subtractFromRecipientIdSelect.appendChild(opt);		


			// Make the remove button visible again for all recipient components
			setVisibilityRemoveRecipientButton();

			// control visibility  and vertical spaces
			if (getRecipientIds().length == 1) {
				FeeSelectionComponent.showSubtractFrom(false);
				document.getElementById('vertical-space-for-subtract-fees-from-amount-checkbox').style['margin-top'] = '0px';
			} else {
				document.getElementById('vertical-space-for-subtract-fees-from-amount-checkbox').style['margin-top'] = '60px';
				if (document.getElementById('subtract').checked) {
					FeeSelectionComponent.showSubtractFrom(true)
				}
			}

		} 

		function removeRecipient(recipientId=-1) {	
			if (recipientId==-1) {
				recipientId = getRecipientIds().length - 1
			};
			let recipients = document.getElementById('recipients');

			// This removes the recipient div 
			for (var i = recipients.children.length -1; i >= 0; i--) {
				let	child =  recipients.children[i];
				if (child.recipientId == recipientId) {
					recipients.removeChild(child)
				}
			}

			// This removes the recipientId from the subtract_from_recipient_id_select
			var subtractFromRecipientIdSelect = FeeSelectionComponent.subtractFrom.children.subtract_from_recipient_id_select;
			for (var i = subtractFromRecipientIdSelect.children.length -1; i >= 0; i--) {
				let	child =  subtractFromRecipientIdSelect.children[i];
				if (child.value == recipientId) {
					subtractFromRecipientIdSelect.removeChild(child)
				}
			}

			// Not strictly necessary but better to have it to avoid any divergence
			FeeSelectionComponent.subtractUpdated();

			// Hide the remove button if we only have one recipient
			setVisibilityRemoveRecipientButton();

			// control visibility  and vertical spaces
			if (getRecipientIds().length == 1) {
				FeeSelectionComponent.showSubtractFrom(false);
				document.getElementById('vertical-space-for-subtract-fees-from-amount-checkbox').style['margin-top'] = '0px';
			} else {
				document.getElementById('vertical-space-for-subtract-fees-from-amount-checkbox').style['margin-top'] = '60px';
			}
		}

		function toggleTextUnit(unitSelected) {
			textUnit = unitSelected.value
		}

		function isAboveWalletBalance(unit, amount) {
			// TODO: Currently check is disabled for RBF for simplicity, should add it back for RBF
			if ("{{rbf_tx_id}}") {
				return false;
			}
			if(unit in assetBalances){
				return amount > assetBalances[unit].balance;
			}else{
				return amount > 0;
			}
		}

		function isInvalidValue(unit, amount){
			if (!amount) {
				return false;
			}
			return (unit == 'sat' ? amount / 1e8 : amount) < 1e-8;
		}

		async function setMaxAmount(recipientId) {
			const recipients = getRecipients();
			const recipient = document.getElementById(`recipient_${recipientId}`);
			FeeSelectionComponent.showSubtractFrom(true)
			FeeSelectionComponent.setSubtractFrom(recipientId)
			if (!validAddress(recipientId)) {
				return;
			}
			FeeSelectionComponent.setSubtract(recipient.unit == 'sat' || recipient.unit == 'btc' || recipient.unit == 'lbtc');

			let othersAmount = 0;
			for(let j in recipients) {		
				other_recipient = recipients[j]		;
				if (other_recipient.recipientId != recipientId) {
					let unit = other_recipient.unit;
					let amount = other_recipient.amount;
					// assets
					if(other_recipient.unit != 'sat' || other_recipient.unit != 'btc'){
						if(unit == recipient.unit){
							othersAmount += amount;
						}
					// btc
					}else{
						if(unit == 'sat' || unit == 'btc'){
							othersAmount += (unit == 'sat' ? amount / 1e8 : amount);
						}
					}
				}
			}

			let maxAmount = (coinselectionWebcomponent.getSpendableAmount(recipient.unit) - (recipient.unit == 'sat' ? othersAmount * 1e8 : othersAmount));
			if (recipient.unit == 'sat') {
				maxAmount = Math.round(maxAmount);
			} else {
				maxAmount = parseFloat(maxAmount.toFixed(8));
			}
			if (maxAmount < 0) {
				maxAmount = 0;
			}
			document.getElementById(`recipient_${recipientId}`).amount = maxAmount;
		}

		// Form validation
		function validateAmount(unit, amount, recipientId, allowZero=false) {
			if (isNaN(amount)) {
				showError(`{{ _("Amount entered is invalid!") }}`, 5000);
				return false;
			}
			if (recipientId) {				
				if (coinselectionWebcomponent != null) {
					document.getElementById(`recipient_${recipientId}`).max = coinselectionWebcomponent.getSpendableAmount(unit);
				} else {
					document.getElementById(`recipient_${recipientId}`).max = spendableAmount
				}
			}
			if (!amount && !allowZero) {
				showError(`{{ _("Amount is zero.") }}`, 5000);
				return false;
			}
			if (isAboveWalletBalance(unit, amount)) {
				showError(`{{ _("You cannot send more than") }} ${assetBalances[unit].balance} ${assetBalances[unit].label}!`, 5000);
				return false;
			} 
			// Directly checks coin selection in here
			else if (coinselectionWebcomponent.shouldSelectMoreCoins(unit, amount)) {
				showError(`{{ _("You need to select more coins!") }}`, 5000);
				return false;
			} 
			else if (isInvalidValue(unit, amount)) {
				showError(`{{ _("Invalid amount! Wrong unit?") }}`, 5000);
				return false;
			} 
			else {
				return true;
			}
		}

		// Returns true if the address is valid 
		function validAddress(recipientId) {
			let reWhite = /\s/;
			let address = document.getElementById(`recipient_${recipientId}`).address;
			if (!address) {
				showError(`{{ _("You provided no address.") }}`, 5000);
				return false
			}
			// Segwit addresses are always between 14 and 74 characters long.
			else if (address.length < 14) {
				showError(`{{ _("Please provide a valid address!") }}`, 5000);
				return false
			}
			else if (reWhite.test(address)) {
				showError(`{{ _("Looks like there are whitespaces in the address field.") }}`, 5000);
				return false
			}
			else {
				return true;
			}
		}

		// Returns true if the fee is valid
		function validFee() {
			let feeRate = FeeSelectionComponent.selectedFee()
			if (feeRate == '') {
				showError(`{{ _("You didn't input a number for the fee or left it empty.") }}`, 5000)
				return false	
			}
			else if (feeRate < MIN_FEE_RATE) {
				showError(`{{ _("Your fee is too low. The minimum fee for ${NETWORK} is ${MIN_FEE_RATE} satoshi.") }}`, 5000)
				return false	
			}
			else {
				return true
			}
		}

		function validateForm(submitted=false) {
			const recipients = getRecipients();
			// this assures that the 'recipient_dicts' input has the newest recipientDicts
			document.getElementById('recipient_dicts').value  = JSON.stringify(getRecipientDicts());  
			console.log("validateForm is called")
			let createPSBTButton = document.getElementById('create_psbt_btn');
			// Disables submit but button still clickable before every validation
			createPSBTButton.setAttribute('type', 'button');
			let totalAmount = 0.0;
			let assetAmounts = {};
			if (document.getElementById('ui-radio-btn').checked) {
				for(let i in recipients) {
					let recipient = recipients[i];
					if(recipient.unit == 'btc' || recipient.unit == 'sat'){
						totalAmount += (recipient.unit == 'sat' ? recipient.amount / 1e8 : recipient.amount);
					}else{
						if(recipient.unit in assetAmounts){
							assetAmounts[recipient.unit] += recipient.amount;
						}else{
							assetAmounts[recipient.unit] = recipient.amount;
						}
					}


					if (submitted) {
						// Check address
						if (!validAddress(recipient.recipientId)) {
							return;
						}
						// Check amount
						if (!validateAmount(recipient.unit, recipient.amount, recipient.recipientId)) {
							return;
						}
					}
				}
				// Check fee selection
				if (submitted) {
					if (!validFee()) {
					return
					}	
				}
	
			} else {
				let outputs = document.getElementById('recipients-txt').value.split('\n');
				for (let output of outputs) {
					if (textUnit == 'sat') {
						totalAmount += parseInt(output.split(',')[1].trim()) / 1e8;
					} else {
						totalAmount += parseFloat(output.split(',')[1].trim());
					}
				}
			}

			// Check Liquid assets
			for(asset in assetAmounts){
				if(!validateAmount(asset, assetAmounts[asset])){
					return;
				}
			}
			// Necessary since recipients can be removed which leades to
			// mismatches between the index in the get_recipient_list and the selected recipientId
			indexSubtractFromRecipient = getRecipientIds().indexOf(parseInt(FeeSelectionComponent.subtractFromRecipientIdSelect.value, 10));
			FeeSelectionComponent.setSubtractFrom(indexSubtractFromRecipient)
			createPSBTButton.setAttribute('type', 'submit');
			return true;
		}

		// Utils
		function setVisibility(id, visibility) {
			document.getElementById(id).style.display = visibility;
		}

		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;`;
			} else {
				advancedSettings.style.display = 'block';
				advancedButton.innerHTML = `{{ _("Advanced") }} &#9660;`;
			}
		}

		function toggleSendUIType(radioBtn) {
			if (radioBtn.value == 'ui') {
				FeeSelectionComponent.removeLineBreaks()
				setVisibility('recipients', 'block');
				setVisibility('add-recipient', 'flex');
				setVisibility('recipients-txt-container', 'none');
				setVisibility('subtract', 'block');
				if (getRecipientIds().length <= 1) {
					FeeSelectionComponent.showSubtractFrom(false)
				}
			} else {
				setVisibility('recipients', 'none');
				setVisibility('add-recipient', 'none');
				setVisibility('recipients-txt-container', 'block');
				// Assumes that text is always used for multiple recipients
				if (document.getElementById('subtract').checked) {
					FeeSelectionComponent.showSubtractFrom(true)
					// Adds two line breaks after the RBF checkbox, since it gets crowded
					FeeSelectionComponent.addLineBreaks(2)
				}
			}
		}

		async function calculateEstimatedFee() {
			document.getElementById('calculated_tx_fee').innerText = ``;
			if (await validateForm(true) !== true) {
				return;
			}
			try {				
				var formData = new FormData(document.getElementById('send-form'));
				let url="{{ url_for('wallets_endpoint_api.estimate_fee', wallet_alias=wallet.alias) }}"
				formData.append("estimate_fee", true)
			
				let result = await send_request(url, 'POST', "{{ csrf_token() }}", formData);
				console.log(result);
				if (result.success) {
					let psbt = result.psbt;
					let fees = parseInt(psbt.fee * 1e8)
					document.getElementById('calculated_tx_fee').innerText = `: ${fees} sats`;
					if('{{ specter.price_check }}' == 'True'){
						let altRate = parseFloat('{{ specter.alt_rate }}');
						let altSymbol = '{{ specter.alt_symbol }}';
						let altAmount = parseFloat((altRate * fees / 1e8).toFixed(2))
						if (!isNaN(altAmount) && (altSymbol && altRate)) {
							document.getElementById('calculated_tx_fee').innerText = `: ${fees} sats (${altAmount}${altSymbol})`;
						}
					}
					return fees;
				} else {
					document.getElementById('calculated_tx_fee').innerText = `: ${result.error}`;
				}
			} catch (e) {
				console.log(e);
				document.getElementById('calculated_tx_fee').innerText = `: {{ _("Failed to calculate transaction fees.") }}`;
			}
			return -1;
		}

		document.addEventListener("DOMContentLoaded", function() {
			{% if fillform %}
				{% for addr, amount, amount_unit, label in recipients %}
				addRecipient("{{ addr }}", {{ amount }}, "{{ amount_unit }}", "{{ label }}");
				{% endfor %}
			{% else %}
				addRecipient("", "", "btc", "");
			{% endif %}
				adjustForLiquid()
				document.getElementById('toggle_advanced').addEventListener('click', (event) => {
					toggleAdvanced();
				});
			// Hide the remove button if the page is loaded with only once recipient 
			setVisibilityRemoveRecipientButton();
		});
	</script>
{% endblock %}
