"use strict";

$(function() {

    new class {

        benElements = "<h6 class='mb-2'>Beneficiaries</h6>";
        form;

        constructor() {

            this.form = $("form#transfer-form").get(0);

            this.controlEyedrop();
            this.reactiveCharge();
            // this.autofill(); // For testing
            this.resendEmailOTP();
            this.loadingTransfer();
            this.managerTransaction();
            this.loadBeneficiary();
            this.reactiveIdentifier();

        }

        controlEyedrop() {

            $('#eyedrop').click(function() {

                $('[data-area="asterik"]').toggleClass('d-none');
                let visible = !$('[data-area="balance"]').toggleClass('d-none').hasClass('d-none');

                let swap = visible ? ['bi-eye', 'bi-eye-slash'] : ['bi-eye-slash', 'bi-eye'];

                $(this).find('.bi').removeClass(swap[0]).addClass(swap[1]);

            });

        }

        reactiveCharge() {
            let self = this;
            $("[data-amount]").on('input', function() {

                // Modify Value;
                let value = this.value.replace(/[^\d,.]+/ig, '').split('.');

                // Get Integer
                let unit = value[0].replace(/[^\d]+/ig, "").trim();
                if( isNaN(unit) ) {
                    if( unit.trim() != '' ) {
                        this.value.substr(0, this.value.length - 1);
                    }
                };

                // Get Decimal
                let dec = value[1];
                value = [unit];
                if( dec !== undefined ) {
                    dec = dec.replace(/[^\d]+/ig, '').trim();
                    value[1] = dec;
                };

                // Calculate Charges;
                let charge = self.charge( value.join('.') );
                let fee = charge.toLocaleString();
                if( fee == '0' ) fee = '0.00';
                $("[data-charge]").text( fee );

                self.#rewriteAmountValue( value );

            });
        }

        #rewriteAmountValue( value ) {
            
            let el = $(this.form).find("[data-amount]").get(0);
            let selectStart = el.selectStart;

            let locale = [];
            $(this.form).find(`[name='amount']`).val( Number(value.join('.')) );

            // Locale;
            locale[0] = value[0];
            if( locale[0] != '' ) {
                locale[0] = Number(locale[0]).toLocaleString();
                if( value[1] != undefined ) {
                    locale[1] = value[1];
                };
            };

            // Values;
            let inputValue = value.join('.');
            let localeValue = locale.join('.');

            // Length difference
            let lengthDiff = localeValue.length - inputValue.length;
            
            $(el).val( locale.join('.') );

            el.selectEnd = el.selectStart = selectStart + lengthDiff;

        }

        charge( value ) {
            value = parseFloat( value );
            let charge = parseFloat( Uss.charge );
            let fee = value * charge * 0.01;
            if( isNaN(fee) ) fee = 0;
            return fee;
        }

        autofill() {
            let data = {
                amount: 10,
                bank_name: "Zenith Bank Plc",
                bank_account: "1234567890",
                bank_holder: "Uchenna Ajah",
                tx_reason: "To give uche for awoof!"
            };
            for( let x in data ) {
                let value = data[x];
                $("form").find(`[name="${x}"]`).val(value);
            };
            $(`form [name='save_receiver']`).prop('checked', true);
        }

        resendEmailOTP() {
            $('#resend-otp').click(function() {
                let self = this;
                Notiflix.Loading.circle("Please Wait...");
                try {
                    let form = $(this).parents('form').get(0);
                    let input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = self.dataset.name;
                    input.value = '-R';
                    form.appendChild(input);
                    form.submit();
                } catch(e) {
                    Notiflix.Loading.remove();
                    bootbox.alert("Sorry! New OTP could not be resent <br/> Please try again or contact the support team if the problem persist");
                };
            });
        }

        loadingTransfer() {

            let block = $("[data-invoke='loader']").get(0);

            if( !block ) return;

            const __class__ = this;

            let loading = Notiflix.Loading; // Notiflix Loading

            // Loading Processes
            let process = [
                'Please Wait',
                'Checking IP Address',
                'Transaction in progress'
            ];

            // percentage limit
            let min = 7;
            let max = 25;
            let limit = Math.floor(Math.random() * (max - min + 1)) + min;

            // generate percentages
            let percentages = this.#randomNumbers( limit ).map(function(num) {
                return `${num}%`;
            });

            // Extend the process
            process = process.concat( percentages );
            
            // get index
            let index = 0;
            loading.circle( process[index] );
            
            let pause = false;
            
            let interval = setInterval(function() {

                const pause = (Math.random() >= 0.5);
                if( pause ) return;

                index++; // move to next process
                let value = process[index]; // get the value;

                if( !value ) {
                    value = 'Complete! Please wait';
                    clearInterval( interval );
                    __class__.#removeLoader(block);
                };

                loading.change( value );

            }, 500);
            
        }

        #removeLoader(block) {
            let form = $(block).find('form').get(0);
            form.loaded.value = 1;
            setTimeout(function() {
                form.submit();
            }, 1000);
        }

        #randomNumbers(n, max = 100) {
            const arr = [];
            while (arr.length < n) {
                const num = Math.floor(Math.random() * max) + 1;
                if (!arr.includes(num)) {
                    arr.push(num);
                }
            }
            arr.sort((a, b) => a - b);
            return arr;
        }

        managerTransaction() {

            if( !Uss['transaction'] ) return;
            
        }

        loadBeneficiary() {

            const __class__ = this;
            let beneficiaries = Uss.beneficiaries;

            if( !beneficiaries.length ) {

                this.benElements += `<div class='border text-center p-3 rounded'>
                    <i class='bi bi-star me-1'></i> No beneficiary saved
                </div>`;

            } else {

                let template = $('#ben-template').get(0);

                for( let beneficiary of beneficiaries ) {

                    let node = template.content.firstElementChild.cloneNode(true);

                    for( let x in beneficiary.bank_info ) {
                        let value = beneficiary.bank_info[x];
                        $(node).find(`[data-send='${x}']`).text(value)
                    };

                    $(node).find(`[data-send='bank_account']`).text(beneficiary['bank_account']);

                    $(node).find("[data-tag]").text((function() {
                        let name = beneficiary.bank_info['bank_holder'].split(' ').map(function(value) {
                            return value.trim()[0];
                        });
                        return name.join('');
                    })());

                    this.benElements += node.outerHTML + "\n";

                };

            };

            $("#finder").click(function() {
                bootbox.alert({
                    message: __class__.benElements,
                    buttons: {
                        ok: {
                            label: 'Close',
                            className: 'btn-danger'
                        }
                    },
                    onShow: function() {
                        $(this).on('click', "[data-beneficiary]", function() {
                            $(this).find("[data-send]").each(function() {
                                let name = this.dataset.send;
                                let value = $(this).text();
                                $('form#transfer-form').find(`[name='${name}']`).val( value );
                            });
                            bootbox.hideAll();
                        });
                    }
                });
            });

        }

        reactiveIdentifier() {
            $("[name='identifier']").on('change', function() {
                if( this.value.trim() == '' ) {
                    $("#identifier").addClass('d-none');
                } else {
                    $("#identifier").removeClass('d-none').find('[data-identifier]').text( this.value );
                };
            });
        }   

    }

});