//============================== Generic Javascript Functions
var user_config = {
    log: 1,
    theme: 'default',
    menu_default: false, // true - Collapsed | false - Open
    allways_ajax: true
};

function isDefined(data) {
    if (typeof data === 'undefined') {
        return false;
    } else {
        return true;
    }
}

function definedOr(data, value = '') {
    if (typeof data === 'undefined') {
        return value;
    } else {
        return data;
    }
}

function setIfNotEmpty(location, value) {
    if (value != '') {
        $(location).val(value);
    }
}

/*
 * ============================== Template Boot
 *   _______                   _       _
 *  |__   __|                 | |     | |
 *     | | ___ _ __ ___  _ __ | | __ _| |_ ___
 *     | |/ _ \ '_ ` _ \| '_ \| |/ _` | __/ _ \
 *     | |  __/ | | | | | |_) | | (_| | ||  __/
 *     |_|\___|_| |_| |_| .__/|_|\__,_|\__\___|
 *                      | |
 *                      |_|
*/

/* Função de aparecer ou desaparecer o menu lateral */
$(".menu-toggle").on('click', function (e) {
    e.preventDefault();
    //e.preventPropagation();
    $("#wrapper").toggleClass("toggled");
    window.dispatchEvent(new Event('resize'));
});

if (user_config.menu_default) {
    $('#wrapper').addClass('toggled');
    window.dispatchEvent(new Event('resize'));
}

/* Função de aparecer ou desaparecer o menu lateral Secundário*/
$(".menu-toggle").on('contextmenu', function (e) {
    e.preventDefault();
    //e.preventPropagation();
    alert("Configs maluquinhas");
    window.dispatchEvent(new Event('resize'));
});

$('#side-menu').metisMenu();

/*
 * ============================== - MouseTrap
 *  __  __                   _______
 * |  \/  |                 |__   __|
 * | \  / | ___  _   _ ___  ___| |_ __ __ _ _ __
 * | |\/| |/ _ \| | | / __|/ _ \ | '__/ _` | '_ \
 * | |  | | (_) | |_| \__ \  __/ | | | (_| | |_) |
 * |_|  |_|\___/ \__,_|___/\___|_|_|  \__,_| .__/
 *                                         | |
 *                                         |_|
 *
*/

/* Atalho, Ao apertar alt, foca no primeiro ítem do menu lateral */
Mousetrap.bind('alt', function (e) {
    e.preventDefault();
    $('#side-menu li:first-child a').focus();
    $("#wrapper").removeClass("toggled");
    return false;
});

Mousetrap.bind("alt+1", function (e) {
    $("#wrapper").addClass("toggled");
    e.preventDefault();
});

Mousetrap.bind("alt+2", function (e) {
    $('#menu-usuario > li').addClass('open');
    $('#menu-usuario > li >a').focus();
    e.preventDefault();
});

//Foca na barra de pesquisa
Mousetrap.bind("ctrl+shift+f", function (e) {
    $(".search-nav input").focus();
});

function popover_help() {
    $('input').each(function () {
        Mousetrap($(this)[0]).bind('ctrl+f1', function () {
            //alert(10);
        });
    })
}

Mousetrap.bind("ctrl+f1", function (e) {
    //alert(10);
});


//============================== MenuSearch

var menu = Array();
$("#side-menu a").each(function () {
    if ($(this).attr('href') !== "") {
        menu.push("<li>" + $(this).parent().html() + "</li>")
    }
});

$("#side-second-menu").html(menu);

$(".search-nav >input").on("keyup", function () {
    var search = $(this).val().toLowerCase();
    if ($(this).val() === "") {
        $("#side-menu").removeClass("hidden");
        $("#side-second-menu").addClass("hidden");
    } else {
        $("#side-menu").addClass("hidden");
        $("#side-second-menu").removeClass("hidden");
        $("#side-second-menu li").each(function () {
            if ($(this).html().toLowerCase().indexOf(search) > -1) {
                $(this).removeClass('hidden');
            } else {
                $(this).addClass('hidden');
            }
        });
    }
});

/*
 * ============================== - Ajax Page Handler
 *           _              _____
 *     /\   (_)            |  __ \
 *    /  \   _  __ ___  __ | |__) |_ _  __ _  ___  ___
 *   / /\ \ | |/ _` \ \/ / |  ___/ _` |/ _` |/ _ \/ __|
 *  / ____ \| | (_| |>  <  | |  | (_| | (_| |  __/\__ \
 * /_/    \_\ |\__,_/_/\_\ |_|   \__,_|\__, |\___||___/
 *         _/ |                         __/ |
 *        |__/                         |___/
*/


//==============================
//===      Link clicks
//==============================
$('body').on('click', 'a', function (e) {

    if (!user_config.allways_ajax) {
        return true;
    }

    var target = $(this).attr('href');
    var method = $(this).data('method');

    if (typeof target === 'undefined' ||
        target === '' ||
        target === '#' ||
        target == 'javascript:void(0)') {
        return;
    }

    if (method === 'reload' || method === 'follow') {
        return true;
    }

    e.preventDefault();

    if (typeof method === 'undefined') {
        method = 'GET';
    }

    asyncRedirect(target, method);

});

//==============================
//===    Form submissions
//==============================
$('body').on('submit', 'form', async function (e) {

    var formAjax = true;

    if (formAjax == false) {
        return true;
    }

    e.preventDefault();

    let request = await fetch(e.target.action, {
        method: e.target.method,
        body: JSON.stringify($(this).serialize()).replace(/^"+|"+$/g, ''),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'fetch'
        }
    });

    let responseJson = await request.json();

    if (!request.ok) {

        $('#toast-container').bootstrapToastWrapper({
            'type': 'danger',
            'title': 'Erro',
            'body': responseJson,
            'timeout': 5000
        });

    } else {

        $('#toast-container').bootstrapToastWrapper({
            'type': 'success',
            'title': 'Sucesso',
            'body': 'Ação bem sucedida',
            'timeout': 5000
        });

        if (responseJson.location) {
            asyncRedirect(responseJson.location, 'GET');
        }
    }
});

/*
 *  Ao sair do campo digitável de um valor buscavel. Executa a busca
*/
$('#content').on('blur', '[data-search] input', function (e) {
    val = $(this).val();
    if (val == "") { return; }

    el = $(this);
    elwrap = $(this).parent().parent();

    url = $(this).parent().parent().data('search');
    fields = $(this).parent().parent().data('searchfields').split('+');

    fetch(url + val, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'fetch'
        }
    }).then(function (response) {
        let json = response.json();
        return json;
    }).then(function (json) {

        if (json == null) {
            $(this).val('');
            $($(elwrap).find('input')[1]).val("");
            return;
        }

        var fieldData = "";
        for (value in fields) {
            fieldData += json[fields[value]] + " ";
        }
        $($(elwrap).find('input')[1]).val(fieldData);
        $(this).find('input').trigger('filled', json);
        //$(e).trigger('filled', json);
        //console.log();
    });
});


// Revalidate screen
function revalidate_screen(location) {

    $(location).find('[data-mask]').each(function () {
        if ($(this).data('maskreverse') == false) {

        } else {
            var params = {
                reverse: true
            }
        }

        if ($(this).data('maskcomplete')) {
            params.onComplete = window[$(this).data('maskcomplete')]
        }

        $(this).mask($(this).data('mask'), params);

        $(this).on('filled', { 'params': params }, function (e) {
            $(this).mask($(this).data('mask').mask);
            $(this).mask($(this).data('mask').mask, params);
        });

    });

    /*$(location).find('.remoteFill').each(function(i, el){
        $(el).on('click', function(){
            $(this).remoteFill();
        })
    });*/

    //$('[data-toggle="popover"]').popover();

    $(location).find('.remote-element').each(async function () {
        var element = $(this);
        var source = $(this).data('source');
        var value = $(this).data('value');
        source = source + '?value=' + value;
        await asyncFill(source, 'GET', element, revalidate_screen, element);
    });

    $(location).find('.remote-datatable').each(async function () {
        var element = $(this);
        var source = $(this).data('source');
        var value = $(this).data('value');
        await asyncFill(source, 'GET', element, datatableInplaceBoot, $(this));
    });

    setSelectValues(location);
    datatableBasicBoot();

    $('.icon-colapser').on('click', function () {
        $(this).parent().parent().find('.panel-collapse').collapse('toggle');
    });

    $(location).find('[data-tablesearch]').on('click', async function (e) {
        await asyncFill(
            $(e.currentTarget).data('tablesearch'),
            'GET',
            $('#modal .modal-body'),
            datatableBasicBoot,
            function (el) {
                $(el).on('click', 'button', function (ee) {
                    $($(modalTarget).find('input')[0]).val($(ee.currentTarget).data('id')).trigger('blur');
                    modal.toggle();
                })
            });

        await openModal({
            'target': $(e.currentTarget).parent().parent().parent(),
            'source': $(e.currentTarget).data('search')
        });
    });

    $(location).find('[data-tablesearchadd]').on('click', async function (e) {
        await asyncFill(
            $(e.currentTarget).data('tablesearchadd') + '/table',
            'GET',
            $('#modal .modal-body'),
            datatableBasicBoot,
            async function (el) {
                await $(el).on('click', 'button', async function (ee) {
                    modalTarget.trigger('added', $(ee.target).data('id'));
                    modal.toggle();
                })
            });

        await openModal({
            'target': $(e.currentTarget).parent().parent().find('.list-group'),
            'source': $(e.currentTarget).data('search')
        });
    });

    $(location).find('[data-ean] button').on('click', function (e) {

        $('#modal .modal-body').html('<div id="reader" width="600px"></div>');

        function onScanSuccess(decodedText, decodedResult) {
            // handle the scanned code as you like, for example:
            $(this).parent().find('input').val(decodedText);
            myModal.hide();
        }

        scan = new Html5QrcodeScanner(
            "reader",
            { fps: 10, qrbox: { width: 250, height: 250 } },
            /* verbose= */ false);

        scan.render(onScanSuccess);

        openModal({
            'target': $(e.currentTarget).parent().parent().find('.list-group'),
            'source': $(e.currentTarget).data('search'),
            'close': function () {
                scan.stop();
            }
        });

    });

    /*
     * Campos que se autopreenchem quando o valor é buscado
     */
    $(location).find('[data-listener]').each(function (el, i) {
        var element = $(this);
        let selector = "[name='" + $(this).data('listener') + "']";
        let key = $(this).data('listenervalue');
        $(selector).on('filled blur', function (e, data, data1) {
            console.log($(this));
        });
    });

    /* TODO create validation rules */
    $('#content').find('form').each(function () {
        //$(this).validator();
    });

    popover_help();
}

/*
 * ================================================
 *   _____        _        _        _     _
 *  |  __ \      | |      | |      | |   | |
 *  | |  | | __ _| |_ __ _| |_ __ _| |__ | | ___  ___
 *  | |  | |/ _` | __/ _` | __/ _` | '_ \| |/ _ \/ __|
 *  | |__| | (_| | || (_| | || (_| | |_) | |  __/\__ \
 *  |_____/ \__,_|\__\__,_|\__\__,_|_.__/|_|\___||___/
 *
 */

function datatableBasicBoot(param) {
    $('.datatable').each(function (i, el) {

        var columns = [];

        $(this).find('thead').find('th').each(function (i, el) {
            columns.push({ 'data': $(el).data('field') });
        });

        var ajax = {
            "url": $(el).data('src'),
            'type': 'POST',
        }

        $(el).DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": ajax,
            "columns": columns
        });

        param(el);
    });
}

function datatableInplaceBoot(location = '#content', param = function () { }) {
    $(location).find('.datatable').each(function (i, el) {

        var columns = [];

        $(this).find('thead').find('th').each(function (i, el) {
            columns.push({ 'data': $(el).data('field') });
        });

        var ajax = {
            "url": $(el).data('src'),
            'type': 'POST',
        }

        $(el).DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": ajax,
            "columns": columns
        });

        param(el);
    });
}

function datatableRemoteLoad() {

}

/*
 * ================================================
 *   _____      _           _
 *  / ____|    | |         | |
 * | (___   ___| | ___  ___| |_ ___
 *  \___ \ / _ \ |/ _ \/ __| __/ __|
 *  ____) |  __/ |  __/ (__| |_\__ \
 * |_____/ \___|_|\___|\___|\__|___/
 *
*/

function setSelectValues(select, value) {
    if ($(select).prop('nodeName') == 'SELECT') {
        setSelectValue(select, $(select).data('value'));
    } else {
        $(select).find('select').each(function (i, el) {
            if (typeof $(this).data('value') !== "undefined" && $(this).data('value') !== '') {
                setSelectValue($(this), $(this).data('value'))
            }
        });
    }
}

function setSelectValue(select, value) {
    $(select).find('option').each(function (i, el) {
        $(el).attr('selected', false);
        if ($(el).val() == value) {
            $(el).attr('selected', true);
        }
    });
}

function setSelectName(select, value) {
    $(select).find('select').each(function (i, el) {
        if (typeof $(this).data('value') !== "undefined" && $(this).data('value') !== '') {
            setSelectName($(this), $(this).data('value'))
        }
    });
}

function setSelectName(select, value) {
    $(select).find('option').each(function (i, el) {
        $(el).attr('selected', false);
        if ($(el).html() == value) {
            $(el).attr('selected', true);
        }
    });
}

$('#content').on('reloaded', function () {
    revalidate_screen('#content');
});

revalidate_screen('body');