<template id="address-row">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
    <style>
        @media (max-width: 690px){
            .index {
                max-width: 10px;
            }
            .address {
                max-width: 160px;
            }
        }
        .address-row:hover {
            background-color: var(--cmap-bg-lightest);
        }
    </style>
    <tr class="address-row">
        <td class="index"></td>
        <td class="address">
            <span class="explorer-link"></span>
        </td>
        <td class="label optional"></td>
        <td class="used optional"></td>
        <td class="utxo optional"></td>
        <td class="optional"><span class="amount"></span> <span class="amount-price note hidden">()</span></td>
        <td class="verify optional"><button type="button" class="btn" style="width:150px; max-width:150px;margin: 0px;">{{ _("Verify on device") }}</button></td>
        <td></td>
    </tr>
</template>

<script type="text/javascript">
    /**
     *  Custom element for showing a row in a table of addresses.
        It receive data from component parameters, that are:
        - data-btc-unit: Bitcoin unit to display amounts with. Either "btc" or "sat"
        - data-price: BTC price for price calculations
        - data-symbol: Currency symbol for price calculations
        - data-address: Address information (JSON with the properties: index, address, label, used, utxo, amount)
        - data-wallet: The wallet alias
     */
    class AddressRowElement extends HTMLElement {
        constructor() {
            super();
            var shadow = this.attachShadow({ mode: 'open' });
            var style = document.getElementById('address-row').content;
            var clone = style.cloneNode(true);
            this.el = clone.querySelector(".address-row");

            this.index = clone.querySelector(".index");
            this.address = clone.querySelector(".address .explorer-link");
            this.label = clone.querySelector(".label");
            this.used = clone.querySelector(".used");
            this.utxo = clone.querySelector(".utxo");
            this.amountText = clone.querySelector(".amount");
            this.amountPrice = clone.querySelector(".amount-price");
            this.verify = clone.querySelector(".verify");
            // Attach the created element to the shadow dom
            shadow.appendChild(clone);
        }

        /**
         * Browser calls this method when the element is added to the document
         * (can be called many times if an element is repeatedly added/removed)
        */
        connectedCallback() {
            this.isVerifyQR = this.getAttribute('data-verify-qr') == 'True';
            this.isVerifyHwi = this.getAttribute('data-verify-hwi') == 'True';
            this.addressData = JSON.parse(this.getAttribute('data-address'));
            this.wallet = this.getAttribute('data-wallet');
            this.btcUnit = this.getAttribute('data-btc-unit');
            this.price = this.getAttribute('data-price');
            this.symbol = this.getAttribute('data-symbol');
            this.hideSensitiveInfo = this.getAttribute('data-hide-sensitive-info') == 'true';

            this.index.innerText = `#${this.addressData.index}`;
            this.address.innerHTML = this.hideSensitiveInfo ? '###########################' : this.addressData.address.substring(0, 7) + "&hellip;" + this.addressData.address.substring(this.addressData.address.length - 7);
            if (!this.hideSensitiveInfo) {
                this.address.onclick = () => {
                    showAddressData(this.amountText.innerText, this.amountPrice.innerText, this.addressData, this.wallet);
                }
            }

            if  (this.hideSensitiveInfo) {
                this.label.innerHTML = '############'
            } else {
                this.label.innerHTML = `<address-label \
                    data-address="${this.addressData.address}" \
                    ${this.addressData.label ? `data-label="${this.addressData.label}"` : ''} \
                    ${this.addressData.service_id ? `data-service-id="${this.addressData.service_id}"` : ''} \
                    data-wallet="${this.wallet}"></address-label>`;
            }
            this.used.innerText = this.hideSensitiveInfo ? '###' : `${this.addressData.used ? 'Yes' : 'No'}`;

            this.utxo.innerText = this.hideSensitiveInfo ? '###' : this.addressData.utxo;
            
            if (this.addressData.assets) {
                this.assetsCount = Object.keys(this.addressData.assets).length;
            } else {
                this.assetsCount = 0;
            }

            this.amount = parseFloat(this.addressData.amount.toFixed(8));

            if (!this.isVerifyQR && !this.isVerifyHwi) {
                this.verify.classList.add('hidden');
            } else {
                this.verify.onclick = async () => {
                    let url = `{{ url_for('wallets_endpoint_api.addressinfo', wallet_alias='WALLET_ALIAS') }}`.replace("WALLET_ALIAS", this.wallet);
                    var formData = new FormData();
                    formData.append('address', this.addressData.address)
                    formData.append('csrf_token', '{{ csrf_token() }}');
                    try {
                        const response = await fetch(
                            url,
                            {
                                method: 'POST',
                                body: formData
                            }
                        );
                        if(response.status != 200){
                            showError(await response.text());
                            return;
                        }
                        const jsonResponse = await response.json();
                        if (jsonResponse.success) {
                            console.log(jsonResponse);
                            let descriptor = jsonResponse.descriptor;
                            let xpubs_descriptor = jsonResponse.xpubs_descriptor;
                            displayAddressOnDevice(this.addressData.address, descriptor, xpubs_descriptor);
                            return;
                        }
                        showError(`{{ _("Failed to load address data to display...") }}`);
                    }  catch(e) {
                        showError(`{{ _("Failed to load address data to display...") }}`);
                        showError(e);
                    }
                }
            }
            
            const onlyLBTC = (this.assetsCount == 1 && Object.keys(this.addressData.assets)[0] == "{{ specter.default_asset }}");
            const isLiquid = this.assetsCount > 0;
            if ((isLiquid && !onlyLBTC) || !this.price || !this.symbol || this.hideSensitiveInfo) {
                this.amountPrice.innerText = '';
                this.amountPrice.classList.add('hidden');
            } else {
                if (this.symbol == "$" || this.symbol == "£") {
                    this.amountPrice.innerText = `(${this.symbol}${numberWithCommas((parseFloat(this.price) * this.amount).toFixed(2))})`;
                } else {
                    this.amountPrice.innerText = `(${numberWithCommas((parseFloat(this.price) * this.amount).toFixed(2))}${this.symbol})`;
                }
                this.amountPrice.classList.remove('hidden');
            }

            if (this.btcUnit == 'sat') {
                this.amount = parseInt(this.amount * 1e8);
            }

            if (this.assetsCount > 1) {
                this.amountText.innerText = this.hideSensitiveInfo ? '########' : `Multiple assets`;
            } else if (this.assetsCount == 1) {
                this.amountText.innerHTML = this.hideSensitiveInfo ? '########' : `${numberWithCommas(this.amount.toString())} <asset-label data-asset="${Object.keys(this.addressData.assets)[0]}"></asset-label>`;
            } else {
                this.amountText.innerText = this.hideSensitiveInfo ? '########' : `${numberWithCommas(this.amount.toString())}`;
            }

            if (this.addressData.used > 0) {
                this.el.classList.add('unconfirmed');
            }
        }
    }

    customElements.define('address-row', AddressRowElement);
</script>