"use strict";

$(function() {

    new class {
        
        form;
        fee;
        currency = {};

        constructor() {
            this.form = $("form").get(0);
            this.fee = Number(Uss.exchange_fee);
            this.#computeValue();
            this.#setReaction( this );
        }

        getElementByName( name, event, func ) {
            let el = $(this.form).find(`[name='${name}']`).get(0);
            if( el && typeof event == 'string' && typeof func == 'function' ) {
                $(el).on(event, func);
            };
            return el;
        }

        #computeValue() {
            this.currency.from = this.getElementByName('paid_currency').value;
            this.currency.to = this.getElementByName('expected_currency').value;
            this.currency.input = Number( this.getElementByName('paid_amount').value );
            if( isNaN(this.currency.input) ) {
                this.currency.input = 0;
            };
            this.currency.input = Math.abs( this.currency.input );
            let inputCoin = this.#getCoin(this.currency.from);
            this.currency.USD = this.currency.input / inputCoin.rate;
            this.currency.USDFee = this.currency.USD * this.fee * 0.01;
            this.currency.USDTotal = this.currency.USD - this.currency.USDFee;
            let outputCoin = this.#getCoin(this.currency.to);
            this.currency.exchange = this.currency.USD * outputCoin.rate; // Without Fee
            this.currency.output = this.currency.USDTotal * outputCoin.rate; // With Fee
            this.#updatePostField();
        }

        #updatePostField() {
            this.getElementByName('expected_amount').value = this.currency.output.toFixed(2);
            this.getElementByName('usd_value').value = this.currency.USD.toFixed(2);
            this.getElementByName('usd_fee').value = this.currency.USDFee.toFixed(2);
        }

        #setReaction( __class__ ) {
            this.getElementByName('paid_currency', 'change', this.#computeValue.bind(this));
            this.getElementByName('paid_amount', 'input', this.#computeValue.bind(this));
            this.getElementByName('expected_currency', 'change', function() {
                __class__.#computeValue();
                $("#expected-unit").text( this.value );
            });
        }

        #getCoin( code ) {
            for( let coin of Uss.currency ) {
                if( coin.code == code ) {
                    coin.rate = Number(coin.rate);
                    return coin;
                }
            }
        }

    };

});