// Startup function
$(function () {
    $('#sm-wifi-info-button').popover(
        {
            trigger: 'manual',
            placement: 'right',
            html: true,
            title: "WiFi Manager",
            content: function () {
                return "<p><strong>WiFi Manager</strong> controls StellarMate WiFi mode." +
                    " By default StellarMate runs in <b>HotSpot</b> mode where it creates its own network. You can also join StellarMate to your" +
                    " existing home WiFi network by switching to <b>Infrastructure</b> mode.</p>";
            }
        });

    loadInterfaces();
    loadSSIDs();

    $('#sm-mode-hotspot').confirmation({
        onConfirm: function () {
            $.ajax({type: 'POST', url: '/api/system/forget_wifi'});
            $("#sm-wifi-message").attr("class", "alert alert-warn");
            $("#sm-wifi-message").html("Switching to HotSpot Mode... Wait for HotSpot network to activate, connect to it," +
                " and then refresh this page."
                + "<div class='row justify-content-center'><i class='fas fa-spinner fa-spin fa-7x'></i></div>");
            $(".container").css("filter", "grayscale(100%)")
            //$(".container").css("filter", "brightness(50%)")
        }
    });

    $('#sm-mode-infrastructure').confirmation({
        onConfirm: function () {
            $("#sm-wifi-message").html("Select network SSID and then enter its password and press connect.");

            $("#sm-mode-hotspot").removeClass("btn-primary");
            $("#sm-mode-infrastructure").addClass("btn-primary");

            $("#sm-ssid-block").show();
            $("#sm-pass-block").show();
            $("#sm-connect-block").show();

        }
    });

    $("#sm-ssid-connect").on('click', function (event) {
        event.preventDefault();

        $(".container").css("filter", "grayscale(100%)");
        $("#sm-wifi-message").attr("class", "alert alert-warn");
        $("#sm-wifi-message").html("Connecting to WiFi Network... Wait 30-60 seconds and then refresh this page again."
                + "<div class='row justify-content-center'><i class='fas fa-spinner fa-spin fa-7x'></i></div>");

        const credentials = {ssid: $("select option:selected").val(), psk: $("#sm-ssid-password").val()};

        //console.log(JSON.stringify(credentials));

        $.ajax({
        type: 'POST',
        url: encodeURI("/api/system/configure_wifi"),
        data: JSON.stringify(credentials),
        contentType: "application/json; charset=utf-8",
        success: function() {
            $.ajax({type: 'POST', url: '/api/system/select_wifi'});
        },
        error: function(xhr, ajaxOptions, thrownError) {
            $(".container").css("filter", "");
            $("#sm-wifi-message").attr("class", "alert alert-error");
            $("#sm-wifi-message").html("Failed to connect to WiFi network: " + xhr.responseText + ". Check password and try again.");
        }
    });


    });

    $("#show_hide_password button").on('click', function (event) {
        event.preventDefault();
        if ($('#show_hide_password input').attr("type") === "text")
        {
            $('#show_hide_password input').attr('type', 'password');
            $('#show_hide_password span').addClass("fa-eye-slash");
            $('#show_hide_password span').removeClass("fa-eye");
        } else if ($('#show_hide_password input').attr("type") === "password")
        {
            $('#show_hide_password input').attr('type', 'text');
            $('#show_hide_password span').removeClass("fa-eye-slash");
            $('#show_hide_password span').addClass("fa-eye");
        }
    });
});

function loadInterfaces()
{
    $.getJSON("/api/info/interfaces", function (jsonResponse) {
        if (jsonResponse)
        {
            const wifiFace = jsonResponse.find(iface => iface.interface === 'wlan0');
            if (wifiFace)
            {
                const ip = wifiFace.ip;
                $("#sm-wifi-ip").text(ip);
                if (ip === "10.250.250.1")
                {
                    $("#sm-mode-hotspot").addClass("btn-primary");
                    $("#sm-mode-infrastructure").removeClass("btn-primary");

                    $("#sm-ssid-block").hide();
                    $("#sm-pass-block").hide();
                    $("#sm-connect-block").hide();

                    $("#sm-wifi-message").attr("class", "alert alert-info");
                    $("#sm-wifi-message").text("Connected to HotSpot.");

                } else
                {
                    $("#sm-mode-hotspot").removeClass("btn-primary");
                    $("#sm-mode-infrastructure").addClass("btn-primary");

                    $("#sm-ssid-block").show();
                    $("#sm-pass-block").show();
                    $("#sm-connect-block").show();

                    $("#sm-wifi-message").attr("class", "alert alert-info");
                    $("#sm-wifi-message").text("Connected to WiFi.");
                }

                console.log(JSON.stringify(wifiFace));
            }
        }
    });
}

function loadSSIDs()
{
    $.getJSON("/api/info/active_connections", function (conns) {
        if (conns)
        {
            $.getJSON("/api/info/wifi", function (ssids) {
                if (ssids)
                {
                    $("#sm-ssid-list").empty();

                    for (const ssid of ssids.result)
                    {
                        console.log(JSON.stringify(ssid));
                        if (conns.some(con => con.id === ssid.ssid))
                            $("#sm-ssid-list").append("<option selected>" + ssid.ssid + "</option>");
                        else
                            $("#sm-ssid-list").append("<option>" + ssid.ssid + "</option>");
                    }
                }
            });
        }
    });
}
