// the game itself
var game;

var gameOptions = {

    // slices (prizes) placed in the wheel
    slices: 8,

    // wheel rotation duration, in milliseconds
    rotationTime: 3000,

    prizeWon: null
};

// once the window loads...
window.onload = function () {

    // game configuration object
    var gameConfig = {
        // render type
        type: Phaser.AUTO,
        // game width, in pixels
        width: 600,
        // game height, in pixels
        height: 860,
        // game background color
        //    backgroundColor: 0x111111,
        transparent: true,

        // scenes used by the game
        scene: [playGame]
    };

    // game constructor
    game = new Phaser.Game(gameConfig);

    // pure javascript to give focus to the page/frame and scale the game
    window.focus()
    resize();
    window.addEventListener("resize", resize, false);
}

// PlayGame scene
class playGame extends Phaser.Scene {

    // constructor
    constructor() {
        super("PlayGame");
    }

    // method to be executed when the scene preloads

    preload() {
        // loading assets
        this.load.image("wheel", "/images/wheelnew.svg");
        this.load.image("pin", "/images/pin.png");
        this.load.image("PlayBtn", "/images/PlayBtn.png");
        this.load.image("SpinText", "/images/spin-text.png");
        this.load.setPath('/media/');
        this.load.audio('mountainaAudio', ['audioFinal.mp3']);
        this.load.audio('popupSound', ['popupSound.mp3']);
    }

    // method to be executed once the scene has been created
    create() {
        var PlayBtn;

        // adding the wheel in the middle of the canvas
        this.wheel = this.add.sprite(game.config.width / 2, game.config.height / 2, "wheel");

        // adding the pin in the middle of the canvas
        this.pin = this.add.sprite(game.config.width / 2, game.config.height / 2.06, "pin");

        // adding the text field
        this.prizeText = this.add.text(game.config.width / 2, game.config.height - 2, "", {
            font: "bold 18px Arial",
            align: "center",
            color: "white"
        });

        this.SpinText = this.add.sprite(game.config.width / 2, game.config.height - 800, "SpinText");
        this.PlayBtn = this.add.sprite(game.config.width / 2, game.config.height - 60, "PlayBtn");

        // center the text
        this.prizeText.setOrigin(0.5);

        // the game has just started = we can spin the wheel
        this.canSpin = true;
        // waiting for your input, then calling "spinWheel" function
        this.input.on("pointerdown", this.spinWheel, this);
    }

    // function to spin the wheel
    spinWheel() {
        var mountainaAaudio = this.sound.add('mountainaAudio');
        var popupSoundx = this.sound.add('popupSound');

        // can we spin the wheel?
        if (this.canSpin) {
            mountainaAaudio.play();

            // resetting text field
            this.prizeText.setText("");

            // the wheel will spin round from 2 to 4 times. This is just coreography
            var rounds = Phaser.Math.Between(3, 3);

            // get the selected prize
            // before the wheel ends spinning, we already know the prize according to "degrees" rotation and the number of slices
            gameOptions.prizeWon = decryption($('#set_prize_won').val());

            // then will rotate by a random number from 0 to 360 degrees. This is the actual spin
            var degrees = gameOptions.prizeWon.degree;
            // now the wheel cannot spin because it's already spinning
            this.canSpin = false;

            // animation tweeen for the spin: duration 3s, will rotate by (360 * rounds + degrees) degrees
            // the quadratic easing will simulate friction
            this.tweens.add({
                // adding the wheel to tween targets
                targets: [this.wheel],

                // angle destination
                angle: (360 * rounds) + degrees,

                // tween duration
                duration: gameOptions.rotationTime,

                // tween easing
                ease: "Cubic.easeOut",

                // callback scope
                callbackScope: this,

                // function to be executed once the tween has been completed
                onComplete: function (tween) {
                    mountainaAaudio.stop();
                    this.storeData(popupSoundx);
                }
            });
        }

    }

    storeData(popupSoundx) {
        fetch(gameOptions.api, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            body: JSON.stringify({
                'uuid': gameOptions.uuid,
                'prize_id': gameOptions.prizeWon.id
            })
        }).then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.freeSpin == 0) {
                        // set the variables
                        $('.winTitle').html(gameOptions.prizeWon.title);
                        $('#ProImg').html("<img src='/images/product/" + gameOptions.prizeWon.id + ".png' class='img-fluid'>");
                        $('#ProDesc').html(gameOptions.prizeWon.description);
                        popupSoundx.play();
                        var CloseBtn = document.getElementById('CloseBtn');
                        CloseBtn.addEventListener('click', () => {
                            popupSoundx.stop();
                        });
                        $('#winPopup').show(); $('#winPopupModal').show();
                    }
                    else {
                        $('#winPopup').show(); $('#winPopupFreeSpinModal').show();
                    }
                }
                else
                    window.location.href = '/game/' + gameOptions.uuid;
            }).catch((error) => {
                console.log(error);
            });
    }
}

// pure javascript to scale the game
function resize() {
    var canvas = document.querySelector("canvas");
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    var windowRatio = windowWidth / windowHeight;
    var gameRatio = game.config.width / game.config.height;
}

function decryption(encryptedStr) {
    encryptedStr = CryptoJS.enc.Base64.parse(encryptedStr);
    let encryptData = encryptedStr.toString(CryptoJS.enc.Utf8);
    encryptData = JSON.parse(encryptData);

    let iv = CryptoJS.enc.Base64.parse(encryptData.iv);
    var decryptedData = CryptoJS.AES.decrypt(encryptData.value, CryptoJS.enc.Base64.parse($('#set_key').val().substr(7)), {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    decryptedData = decryptedData.toString(CryptoJS.enc.Utf8);
    // deserialize
    decryptedJson = PHPUnserialize.unserialize(decryptedData);
    return decryptedJson;
}
