$(function () {
    window.addEventListener("message", function (event) {
        if (event.data.type === "HIDE_LICENSE") {
            $("body").fadeOut();
            $("#fName").removeClass("longName");
            $("#lName").removeClass("longName");
        } else if (event.data.type === "SHOW_LICENSE") {
            hide();

            license = event.data.dl;
            
            const dob = new Date(license.Dob);
            const issued = new Date(license.Issued);
            const expired = new Date(license.Expires);

            const dobl = correctDate(dob);
            const issuel = correctDate(issued);
            const expl = correctDate(expired);

            $("#iss").text(issuel);
            $("#expire").text(expl);
            $("#dob").text(dobl);
            $("#fName").text(license.FirstName.toUpperCase());
            $("#lName").text(license.LastName.toUpperCase());
            $("#sex").text(license.Gender.toUpperCase());
            $("#address").text(license.Address);
            $("#class").text(license.Class);
            $("#dd").text((event.data.fake ? dobl : issuel) + "/SADMV/133");
            $("#restrictions").text(license.Restrictions.toUpperCase());

            $("#lNumber").text("C" + license.DisplayId);
            $("#lImage").attr("src", `assets/images/dl${event.data.fake ? "_fake" : ""}.png`);

            let pictureURL = event.data.txd !== "" ? `https://nui-img/${event.data.txd}/${event.data.txd}?v=${Date.now()}` : "assets/images/avatar.png";

            let largeCanvas = document.getElementById("largeCanvas");
            let largePic = new Image();

            largePic.onload = function () {
                this.height = largeCanvas.height;
                this.width = largeCanvas.width;

                scaleToFill(largeCanvas, this);

                if (event.data.fake === true) {
                    noiseifyImage(largeCanvas);
                }
            };

            largePic.src = pictureURL;

            let smallCanvas = document.getElementById("smallCanvas");
            let smallPic = new Image();

            smallPic.onload = function () {
                this.height = smallCanvas.height;
                this.width = smallCanvas.width;

                scaleToFill(smallCanvas, this);

                if (event.data.fake === true) {
                    noiseifyImage(smallCanvas);
                }
            };

            smallPic.src = pictureURL;

            if (license.FirstName.length > 19) $("#fName").addClass("longName");
            if (license.LastName.length > 19) $("#lName").addClass("longName");

            $(".license").show();
            $("#largeCanvas").show();
            $("#smallCanvas").show();
            $("body").fadeIn(500);
        } else if (event.data.type === "SHOW_BADGE") {
            hide();

            const badge = event.data.badge;
            const name = `<strong>${badge.FirstName} ${badge.LastName}</strong>`;
            const unitNumber = `<strong>${badge.UnitNumber}</strong>`;
            const badgeRank = `${badge.Rank}`;
            const badgeId = `${badge.WebsiteId}`;
            const phone = `#${badge.PhoneNumber}`;

            $("#name").html(name);
            $("#uNumber").html(unitNumber);
            $("#rank").html(badgeRank);
            $("#webId").html(badgeId);
            $("#pNumber").html(phone);

            switch (badge.DepartmentId) {
                // LEO
                case 1:
                case 2:
                case 3:
                    $("#lImage").attr("src", "assets/images/leo.png");
                    break;

                // SAFD
                case 5:
                    $("#lImage").attr("src", "assets/images/safr.png");
                    break;
            }

            let pictureURL = event.data.txd !== "" ? `https://nui-img/${event.data.txd}/${event.data.txd}?v=${Date.now()}` : "assets/images/avatar.png";

            const badgeCanvas = document.getElementById("badgeCanvas");
            const largePic = new Image();

            largePic.onload = function() {
                this.height = badgeCanvas.height;
                this.width = badgeCanvas.width;

                scaleToFill(badgeCanvas, this);
            }

            largePic.src = pictureURL;

            $(".badge").show();
            $("#badgeCanvas").show();
            $("body").fadeIn(500);
        }
    });

    function hide() {
        $("body").hide();
        $(".license").hide();
        $(".badge").hide();
        $("#largeCanvas").hide();
        $("#smallCanvas").hide();
        $("#badgeCanvas").hide();
    }

    function correctDate(date) {
        return `${("0" + (date.getMonth() + 1)).slice(-2)}/${("0" + date.getDate()).slice(-2)}/${date.getFullYear()}`;
    }

    function noiseifyImage(canvas) {
        const ctx = canvas.getContext("2d");
        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        let pixels = imageData.data;

        for (let i = 0, il = pixels.length; i < il; i += 4) {
            // generate "noise" pixel
            const color = Math.random() * 255;

            // Apply noise pixel with Multiply blending mode for each color channel
            pixels[i] = pixels[i] * color / 255;
            pixels[i + 1] = pixels[i + 1] * color / 255;
            pixels[i + 2] = pixels[i + 2] * color / 255;
        }

        ctx.putImageData(imageData, 0, 0);
    }

    function scaleToFill(canvas, img) {
        const context = canvas.getContext("2d");
        // get the scale
        const scale = Math.min(canvas.width / img.width, canvas.height / img.height);
        // get the top left position of the image
        const x = ((canvas.width / 2) - (img.width / 2)) * scale;
        const y = ((canvas.height / 2) - (img.height / 2)) * scale;
        context.drawImage(img, x, y, img.width * scale, img.height * scale);
    }
});
