<template>
    <div>
        <section class="section tv-top-container" :class="{'colapse': tvTopContainerColapse}">
            <div class="container is-fullhd">
                <div class="columns">
                    <div class="column is-11 tv-top-column" :class="{'expand': tvTopContainerExpand}">
                        <VueTradingView :options="{
        symbol: 'BINANCE:BTCUSDT',
        theme: 'dark',
        allow_symbol_change: true,
        autosize: true,
        interval: 60,
        hide_side_toolbar: false,
        }" />
                    </div>
                    <div class="column">
                        <span class="icon icon-circle" v-on:click="colapseTvTopContainer">
                            <i class="mdi mdi-24px mdi-arrow-expand-up"></i>
                        </span>
                        <span class="icon icon-circle">
                            <i class="mdi mdi-24px mdi-arrow-expand-all"></i>
                        </span>
                        <span class="icon icon-circle">
                            <i class="mdi mdi-24px mdi-arrow-expand-down" v-on:click="expandTvTopContainer"></i>
                        </span>
                    </div>
                </div>
            </div>
        </section>
        <section class="section filters-bar">
            <div class="container is-fullhd">
                <div class="flex-row flex-middle flex-space">
                    <div>
                        <div class="push-right">
                            <span class="filters-title">
                                <big class="text-primary">FILTERS: </big>
                            </span>

                            <div class="buttons">
                                <span class="button is-dark  is-success is-hovered">Open</span>
                                <span class="button is-dark">Limit 50</span>
                            </div>
                        </div>
                    </div>
                    <div>
                        <big class=""><strong>3COMMAS SMART TRADES/SELLS</strong></big>
                    </div>
                    <div>
                        <span class="filters-title">
                            <big class="text-primary">SORT: </big>
                        </span>

                        <div class="buttons">
                            <a class="button is-dark" @click="sort('profit_percentage'), activeFilter = 'profit'">
                                <span class="icon is-small">
                                    <i class="mdi mdi-24px" :class="[ activeFilter == 'profit' && currentSortDir =='asc' ? 'mdi-chevron-up' : 'mdi-chevron-down' ]"></i>
                                </span>
                                <span>
                                Profit %
                                </span>
                                </a>
                            <a class="button is-dark" @click="sort('id')">Age</a>
                            <a class="button is-dark" @click="sort('to_currency_code')">Coin</a>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        <section class="section">

            <div class="container is-fullhd">
                <div class="columns is-multiline ">
                    <div class="column is-third is-one-quarter-widescreen is-one-third-desktop is-one-third-tablet"
                        v-for="trade in sortedTrades" :key="trade.id">

                        <div class="coin-card is-clear-fix">
                            <div>
                                <div class="tokenicon-wrap is-pulled-left push-right">
                                    <img v-bind:src="'/images/cryptocurrency-icons/svg/color/' + trade.to_currency_code + '.svg'" />
                                </div>
                                <div class="">
                                    <big class="text-primary">{{ trade.to_currency_code }}</big>
                                    <span class="is-pulled-right push-right">
                                        <big :class="{'text-error': trade.profit_percentage < 0, 'text-success': trade.profit_percentage > 0}">{{trade.profit_percentage}}%</big>
                                    </span>
                                </div>

                                <div class="is-pulled-left">
                                    <span class="text-secondary">{{trade.to_currency_name}}</span>
                                </div>

                                <div class="trade-info-small">{{ trade.units_to_buy }} @ {{
                                    formatPrice(trade.buy_price) }} = {{ financial(trade.total) }}BTC
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</template>

<script>
    import VueTradingView from 'vue-trading-view';

    export default {

        data() {
            return {
                trades: {},
                currentSort: 'profit_percentage',
                currentSortDir: 'desc',
                tvTopContainerColapse: false,
                tvTopContainerExpand: false,
            }
        },

        components: {
            VueTradingView,
        },

        methods: {

            colapseTvTopContainer: function () {
                this.tvTopContainerColapse = true;
            },

            expandTvTopContainer: function () {
                this.tvTopContainerExpand = true;
            },

            sort: function (s) {
                //if s == current sort, reverse
                if (s === this.currentSort) {
                    this.currentSortDir = this.currentSortDir === 'asc' ? 'desc' : 'asc';
                }
                this.currentSort = s;
            },

            fetchTrades() {
                axios.get('/api/3commas/gettrades')
                    .then(response => {
                        this.trades = response.data,
                            this.trades.forEach(function (element) {
                                element.profit_percentage = parseFloat(element.profit_percentage)
                            });
                    })
                    .catch(e => {
                        console.log('Error: ', e.response.data)
                    })
            },

            formatPrice(num) {
                if (/\d+\.?\d*e[\+\-]*\d+/i.test(num)) {
                    var zero = '0',
                        parts = String(num).toLowerCase().split('e'), //split into coeff and exponent
                        e = parts.pop(), //store the exponential part
                        l = Math.abs(e), //get the number of zeros
                        sign = e / l,
                        coeff_array = parts[0].split('.');
                    if (sign === -1) {
                        coeff_array[0] = Math.abs(coeff_array[0]);
                        num = '-' + zero + '.' + new Array(l).join(zero) + coeff_array.join('');
                    } else {
                        var dec = coeff_array[1];
                        if (dec) l = l - dec.length;
                        num = coeff_array.join('') + new Array(l + 1).join(zero);
                    }
                }
                return num;
            },

            financial(x) {
                return Number.parseFloat(x).toFixed(8);
            }

        },
        computed: {

            sortedTrades: function () {
                return [].slice.call(this.trades).sort((a, b) => {
                    let modifier = 1;
                    if (this.currentSortDir === 'desc') modifier = -1;
                    if (a[this.currentSort] < b[this.currentSort]) return -1 * modifier;
                    if (a[this.currentSort] > b[this.currentSort]) return 1 * modifier;
                    return 0;
                });
            },

            profitPercentInt: function () {
                return Number(trade.profit_percentage)
            },
        },

        created() {
            this.fetchTrades();
            setInterval(() => this.fetchTrades(), 10000);
        }

    }

</script>
