<template id="tx-row">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='output.css') }}">

   <style>
        .svg-send {
            filter: invert(63%) sepia(67%) saturate(851%) hue-rotate(346deg) brightness(107%) contrast(92%);
        }
        .svg-receive, .svg-immature, .svg-generate {
            filter: invert(61%) sepia(48%) saturate(3609%) hue-rotate(189deg) brightness(91%) contrast(94%);
        }
        .svg-selftransfer, .svg-mixed {
            filter: invert(77%) sepia(68%) saturate(3384%) hue-rotate(44deg) brightness(112%) contrast(74%);
        }
        .svg-cancelled {
            filter: invert(20%) sepia(32%) saturate(4838%) hue-rotate(332deg) brightness(81%) contrast(97%);
        }
        .tx-row {
            vertical-align: middle;
        }
        .frozen {
            background: #48535d
        #546773;
        }
        .frozen:hover {
            background: #48535d
        #546773;
        }
        td {
            height: 100%;
        }
        .address {
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .service-icon {
            margin-top: -5px;
            margin-right: 0.5em;
            height:24px;
            vertical-align: middle;
        }
        .coin_select_checkbox {
            vertical-align: middle;
        }

        .icon-info {
           display: inline-block; 
           position: relative; 
           margin-left: 0.5em; 
        }
       .icon-info .icon-info-text {
            display: none;
            background: #262626;
            border: 1px solid grey;
            border-radius: 5px;
            padding: 0.5em;
            position: absolute;
            left: 30px;
            top: -20px;
            z-index: 2;
        }
        .icon-info .icon-info-text:before, .icon-info .icon-info-text:after {
            content: "";
            position: absolute;
            left: -10px;
            top: 7px;
            border-style: solid;
            border-width: 10px 10px 10px 0;
            border-color: transparent grey;
        }
        .icon-info .icon-info-text:after {
            left: -8px;
            border-right-color: #262626;
        }
        .icon-info .icon-info-text .info-2 {
            display: block;
        }
        .icon-info-text {
            text-transform: capitalize;
            text-align: center;
        }
        .icon-info:hover .icon-info-text, .icon-info:focus .icon-info-text {
            display: inline-block;
        }

    </style>

    <!-- <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}"> -->

    <tr class="tx-row">
        <td id="column-callbackaction" class="callbackaction">
            <input id="coin-select-checkbox" class="checkbox coin_select_checkbox" type="checkbox" name="coinselect" value="" data-cy="selectable-utxo-checkbox">
        </td>
        <td id="column-category">
            <div class="flex items-center space-x-1">
                <div class="icon-info">
                    <img class="category" data-style="vertical-align: middle; margin-right: 10px;"/>
                    <p id="icon-info-text" class="icon-info-text"></p>
                </div>
                <img class="frozen-img hidden svg-white" data-style="vertical-align: middle; height: 28px;" src="{{ url_for('static', filename='img/snowflake.svg') }}"/>
            </div>
        </td>
        <td id="column-txid" class="tx scroll optional txid cursor-pointer" title="Open transaction details">
            <span class="explorer-link"></span>
        </td>
        <td id="column-label" class="tx h-full optional address" style="display: flex; align-items: center;"></td>
        <td id="column-amount">
            <span class="amount"></span> 
            <span class="amount-price note hidden">()</span>
        </td>
        <td id="column-time" class="time optional"></td>
        <td id="column-confirmations">
            <span class="confirmations"></span>
        </td>
        <td class="hidden optional blockhash"></td>
        <td id="column-action" class="highlight-box">
            <div class="flex items-center space-x-1">
                <input class="select-tx-value mr-2" type="hidden" value="">
                <img data-style="vertical-align: middle;" class="select-tx-img" src="{{ url_for('static', filename='img/checkbox-untick.svg') }}" width="25px" data-cy="checkbox-utxo-actions">
                <div data-style="display: flex; justify-content: center; align-items: center; flex-wrap: wrap;">
                    <button class="rbf btn optional hidden" data-style="width: 130px; margin: 2px;" type="button">{{ _("Speed up") }}</button>
                    <button class="rbf-cancel danger btn optional " data-style="width: 130px; margin: 2px;" type="button">{{ _("Cancel transaction") }}</button>
                </div>
            </div>
        </td>
    </tr>
</template>

<script type="text/javascript">
    class TxRowElement extends HTMLElement {
        constructor() {
            super();
            // Create a shadow root
            var shadow = this.attachShadow({mode: 'open'});
            var style = document.getElementById('tx-row').content;
            var clone = style.cloneNode(true);
            this.el = clone.querySelector(".tx-row");

            this.callbackaction = clone.querySelector(".callbackaction");
            this.coinSelectCheckbox = clone.getElementById("coin-select-checkbox");
            this.categoryCell = clone.getElementById("column-category");
            this.category = clone.querySelector(".category");
            this.iconInfoText = clone.getElementById("icon-info-text");
            this.txid = clone.querySelector(".txid .explorer-link");
            this.address = clone.querySelector(".address");
            this.serviceIcon = clone.querySelector(".service-icon");
            this.amountText = clone.querySelector(".amount");
            this.amountPrice = clone.querySelector(".amount-price");
            this.time = clone.querySelector(".time");
            this.confirmations = clone.querySelector(".confirmations");
            this.blockhash = clone.querySelector(".blockhash");        
            this.rbf = clone.querySelector(".rbf");
            this.rbfCancel = clone.querySelector(".rbf-cancel");
            this.selectTxValue = clone.querySelector(".select-tx-value");
            this.selectTxImg = clone.querySelector(".select-tx-img");
            this.frozenImg = clone.querySelector(".frozen-img");

            // Attach the created element to the shadow dom
            shadow.appendChild(clone);
        }

        connectedCallback() {
            this.tx = JSON.parse(this.getAttribute('data-tx'));
            this.wallet = this.getAttribute('data-wallet');
            this.showBlockhash = this.getAttribute('data-show-blockhash') == 'true';
            this.btcUnit = this.getAttribute('data-btc-unit');
            this.price = this.getAttribute('data-price');
            this.symbol = this.getAttribute('data-symbol');
            this.mode = this.getAttribute('data-mode');
            this.hideSensitiveInfo = this.getAttribute('data-hide-sensitive-info') == 'true';
            // Listening for changes of coin selection checkboxes
            this.coinSelectCheckbox.value=`${this.tx['txid']},${this.tx['vout']}` // Necessary?
            this.coinSelectCheckbox.amount = `${this.tx['flow_amount']}` // a bit hackish, doing that to have access via this in next line - necessary?
            this.coinSelectCheckbox.addEventListener("change", (e) => {
                let event = new CustomEvent(('coinSelectRowSelected'), { detail: {
                        txid: this.tx.txid, // Detail currently not used, remove?
                        vout: this.tx.vout,
                        amount: this.amount,
                        locked: this.tx.locked,
                    } }
                );
                this.dispatchEvent(event);
            })
            
            // Set category image
            this.category.src = this.getCategoryImg(this.tx.category, this.tx.confirmations > 0);
            this.category.classList.add('svg-' + this.tx.category)
            this.txid.setAttribute('data-cy', `tx-category-${this.tx.category}`)
            
            // TODO:
            // Setup tx popup for mobile
            if (this.tx.locked) {
                this.el.classList.add('frozen');
                this.frozenImg.classList.remove('hidden')
            }


            // Set txid
            this.txid.innerHTML = this.hideSensitiveInfo ? '############################################' : this.tx.txid.slice(0,11) + '&hellip;';
            if (!this.hideSensitiveInfo) {
                this.txid.onclick = () => {
                    showTxData(
                        this.btcUnit,
                        this.price,
                        this.symbol,
                        this.tx.txid,
                        this.wallet
                    );
                }
            }

            if (window.innerWidth < 690) {
                this.el.onclick = () => {
                    showTxData(
                        this.btcUnit,
                        this.price,
                        this.symbol,
                        this.tx.txid,
                        this.wallet
                    );
                }
            }

            // Set address-label
            if (Array.isArray(this.tx.address)) {
                this.address.innerText = this.hideSensitiveInfo ? '#########' : `${this.tx.address.length} {{ _("Recipients") }}`;
            } else {
                if (this.hideSensitiveInfo) {
                    this.address.innerHTML = '#########';
                } else {
                    if ((typeof services !== 'undefined') && ("service_id" in this.tx) && (this.tx.service_id in services)) {
                        this.address.innerHTML = `<img class="service-icon" src="{{ext_url_prefix}}/${this.tx.service_id}/static/${services[this.tx.service_id].icon}">`;
                    }
                    if (this.tx.label !== undefined) {
                        this.address.innerHTML += `<address-label data-address="${this.tx.address}" ${this.tx.label ? `data-label="${this.tx.label}"` : ''} data-wallet="${this.wallet ? this.wallet : this.tx.wallet_alias}"></address-label>`
                    } else {
                        this.address.innerHTML += this.tx.address;
                    }
                }
            }
            
            // Set amount
            if (this.mode == 'utxo') {
                this.amount = parseFloat(this.tx.amount.toFixed(8))
            } else {
                if (this.tx.flow_amount) {
                    this.amount = parseFloat(this.tx.flow_amount.toFixed(8))
                } else {
                    this.amount = parseFloat(this.tx.amount.toFixed(8))
                }
            }

            if (!this.price || !this.symbol || this.amount == 1e-8 || 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})`;
                }
                if(!("assetlabel" in this.tx) || this.tx.assetlabel == "LBTC"){
                    this.amountPrice.classList.remove('hidden');
                }
            }

            if (this.btcUnit == 'sat' && this.amount != 1e-8) {
                this.amount = parseInt(this.amount * 1e8);
            }

            if (this.amount == 1e-8 ) { //|| this.amount == 0) {
                this.amountText.innerText = '{{ _("Confidential") }}';
            } else {
                if(this.hideSensitiveInfo){
                    this.amountText.innerHTML = '#########';
                }else{
                    this.amountText.innerHTML = `${numberWithCommas(this.amount.toString())}`;
                    if("assetlabel" in this.tx){ // liquid
                        if (Array.isArray(this.tx.assetlabel)) { // multiple assets
                            let unique_assets = this.tx.assetlabel.filter((v, i, a) => { return a.indexOf(v) === i });
                            if (unique_assets.length == 1){
                                this.amountText.innerHTML += ` <asset-label data-asset="${this.tx.asset[0]}" data-label="${this.tx.assetlabel[0]}"></asset-label>`;
                            }else{
                                this.amountText.innerHTML = `${unique_assets.length} assets`;
                            }
                        }else{
                            this.amountText.innerHTML += ` <asset-label data-asset="${this.tx.asset}" data-label="${this.tx.assetlabel}"></asset-label>`;
                        }
                    }
                }
            }

            // Set confirmations
            if (this.tx.confirmations > 0) {
                this.confirmations.innerHTML = this.hideSensitiveInfo ? '########' : `${this.tx.confirmations}`;
            } else if (this.tx.confirmations == 0) {
                this.el.classList.add('unconfirmed');
                this.confirmations.innerHTML = this.hideSensitiveInfo ? '########' : `{{ _("Unconfirmed") }}`;
            } else {
                this.confirmations.innerHTML = this.hideSensitiveInfo ? '########' : `{{ _("Cancelled (replaced by sender)") }}`;
                this.category.src = `{{ url_for('static', filename='img') }}/cross.svg`;
                this.category.classList.remove('svg-' + this.tx.category);
                this.category.classList.add('svg-cancelled');
            }

            if ((this.tx.category == "send" || this.tx.category == "selftransfer") && this.tx["bip125-replaceable"] == "yes" && this.tx["confirmations"] == 0) {
                this.rbf.classList.remove('hidden');
                if (this.tx.category == "selftransfer") {
                    this.rbfCancel.classList.add('hidden');
                } else {
                    this.rbfCancel.classList.remove('hidden');
                    this.rbfCancel.onclick = () => {
                        this.rbfPopup('cancel');
                    }
                }
                this.rbf.onclick = () => {
                    this.rbfPopup('speedup');
                }
            } else {
                this.rbf.classList.add('hidden');
                this.rbfCancel.classList.add('hidden');
            }
            
            // Set time
            if (this.hideSensitiveInfo) {
                this.time.innerText = '###########'
            } else {
                // blocktime for confirmed Txs
                if (this.tx.blocktime) {
                    this.time.innerText = (new Date(this.tx.blocktime * 1000)).toLocaleString()
                } else {
                    this.time.innerText = (new Date(this.tx.time * 1000)).toLocaleString()
                }
            }

            // Show blockhash
            if (this.showBlockhash) {
                this.blockhash.classList.remove('hidden');
                if (
                    this.tx.blockhash &&
                    this.tx.validated_blockhash &&
                    this.tx.validated_blockhash == this.tx.blockhash
                ) {
                    this.blockhash.innerHTML = this.hideSensitiveInfo ? '############################################' : `
                    <explorer-link data-style="word-break: break-all;" data-type="block" data-value="${this.tx.blockhash}"></explorer-link><br>
                    `;
                }
            } else {
                this.blockhash.classList.add('hidden');
            }

            // Select tx option
            if (this.mode == 'utxo') {
                this.selectTxImg.classList.remove('hidden');
                this.selectTxImg.onclick = (e) => {
                    this.selectTxImg.src = this.selectTxValue.value ? `{{ url_for('static', filename='img/checkbox-untick.svg') }}` : `{{ url_for('static', filename='img/checkbox-tick.svg') }}`;
                    this.selectTxValue.value = this.selectTxValue.value ? "" : "true";
                    let event = new CustomEvent('txRowSelected', { detail: {
                        selected: this.selectTxValue.value == "true",
                        txid: this.tx.txid,
                        vout: this.tx.vout,
                        amount: this.amount,
                        locked: this.tx.locked,
                    } });
                    this.dispatchEvent(event);
                    e.stopPropagation(); // this prevent the onclick of outer divs to be triggered
                }
            } else {
                this.selectTxImg.classList.add('hidden');
            }

            // Hide columns
            this.hideColumns = this.getAttribute("hide-columns")
            if (this.hideColumns != "null") {
                this.hideColumns.split(" ").forEach((column_name) => {
                    if (column_name) {
                        let column = this.shadowRoot.getElementById("column-"+ column_name)
                        if (column) {
                            column.remove()
                        }
                    }
                })
            }
        }

        /** 
         * Returns a json from this item
         */
        getTxItem() {
            return this.tx
        }

        isSelected() {
            return this.coinSelectCheckbox.checked
        }

        unselect() {
            this.coinSelectCheckbox.checked = false
        }

        select() {
            this.coinSelectCheckbox.checked = true
        }

        rbfPopup(rbfType) {
            let txDataPopup = document.getElementById('tx-popup');
            let url = `{{ url_for('wallets_endpoint.send_new', wallet_alias='WALLET_ALIAS') }}`.replace("WALLET_ALIAS", this.wallet);
            let newFee = parseFloat((((this.tx.fee * -1) / this.tx.vsize) * 1e8).toFixed(2));
            if (newFee <= 1.02) {
                newFee = 1;
            }
            // TODO: get fee diff from specter
            newFee += 2;
            txDataPopup.innerHTML = 
            `{% if specter.node.alias == "spectrum_node" %}
                <div class="bg-dark-800 p-4 rounded-lg">
                    <h1>RBF not supported yet with Spectrum</h1>
                    <p>If you have to use RBF, you still can. Your transactions have the RBF flag and you can use Specter with Bitcoin Core to speed up or cancel.</p>
                </div>  
            {% else %}
                <div class="bg-dark-800 p-4 rounded-lg">
                    <form action="${url}" method="POST">
                        <h1>${rbfType == 'cancel' ? '{{ _("Cancel") }}' : '{{ _("Speed up transaction") }}'}</h1>
                        <p>{{ _("You can") }} ${rbfType == 'cancel' ? `{{ _("cancel") }}` : `{{ _("speed up") }}`} {{ _("the transaction by increasing its fee rate") }}${rbfType == 'cancel' ? ` {{ _("and sending the funds back to yourself") }}` : ''}:</p>
                        <input type="hidden" name="rbf_tx_id" value='${this.tx.txid}' />
                        <input type="number" min="${newFee}" value="${newFee}" class="fee_rate" name="rbf_fee_rate" id="rbf_fee_rate" min="1" step="any" autocomplete="off" required> sat/vbyte
                        <input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
                        <button class="button mt-2 bg-accent" type="submit" name="action" value="${rbfType == 'cancel' ? 'rbf_cancel' : 'rbf'}" ${rbfType == 'cancel' ? 'danger' : ''}">${rbfType == 'cancel' ? `{{ _("Cancel transaction") }}` : `{{ _("Speed up!") }}`}</button>
                        <span class="toggle_advanced_rbf cursor-pointer">{{ _("Advanced") }} {% if show_advanced_settings %}&#9660;{% else %}&#9654;{% endif %}</span>
                        <div class="advanced_rbf hidden warning flex flex-col">
                            <button class="button mt-2" type="submit" name="action" value="rbf_edit">{{ _("Fully edit the transaction") }}</button>
                        </div>
                    </form>
                </div>
            {% endif %}`;
            let advanceToggle = txDataPopup.querySelector('.toggle_advanced_rbf')
            if (advanceToggle) {
                txDataPopup.querySelector('.toggle_advanced_rbf').onclick = () => {
                    let advancedButton = txDataPopup.querySelector('.toggle_advanced_rbf')
                    let advancedSettings = txDataPopup.querySelector('.advanced_rbf')
                    if (advancedSettings.classList.contains('hidden')) {
                        advancedSettings.classList.remove('hidden')
                        advancedButton.innerHTML = `{{ _("Advanced") }} &#9660;`;
                    } else {
                        advancedSettings.classList.add('hidden')
                        advancedButton.innerHTML = `{{ _("Advanced") }} &#9654;`;
                    }
                }
            }   
            showPageOverlay('tx-popup');
        }

        getCategoryImg(category, isConfirmed) {
            var clockString = isConfirmed ? '' : '-clock';

            switch (category) {
                case "send":
                    return `{{ url_for('static', filename='img') }}/send${clockString}.svg`;
                case "receive":
                    return `{{ url_for('static', filename='img') }}/receive${clockString}.svg`;
                case "immature":
                case "generate":
                    return `{{ url_for('static', filename='img') }}/gear.svg`;
                case "selftransfer":
                    return `{{ url_for('static', filename='img') }}/transfer${clockString}.svg`;
                case "mixed":
                    return `{{ url_for('static', filename='img') }}/mixed${clockString}.svg`;
            }
        }
    }
    customElements.define('tx-row', TxRowElement);
</script>
