$.morpheus.lootbox = {};

const audio = new Audio($.morpheus.base_path + 'plugins/LootBox/assets/sounds/tick.mp3');
const audioWav = new Audio($.morpheus.base_path + 'plugins/LootBox/assets/sounds/tick.wav');

function createRoulette() {
    const $canvas = $("#canvas");

    if ($canvas.length) {
        $.getJSON($.morpheus.base_path + 'lootboxes/' + $canvas.data('id') + "?json=true", function (data) {
            const colors =  $.morpheus.lootbox.colors || [
                '#ccc',
                '#bbb',
                '#aaa'
            ];

            let segments = [];

            let counter = 0;
            for (let i = 0; i < data.items.length; i++) {
                const item = data.items[i];

                if (!colors[counter]) counter = 0;

                segments.push({
                    fillStyle: item.rarity ?? colors[counter],
                    text: item.item.name + ' (' + item.percent + '%)',
                    size: winwheelPercentToDegrees(item.percent)
                });

                counter++;
            }

            const wheel = new Winwheel({
                numSegments: data.items.length,
                outerRadius: 170,
                textFontSize: 12,
                segments: segments,
                animation: {
                    direction: 'anti-clockwise',
                    type: 'spinToStop',
                    duration: 5,
                    spins: 8,
                    soundTrigger: 'pin',
                    callbackFinished: function (e) {
                        $.morpheus.success(wheel.successMessage);
                    },
                    callbackAfter: drawTriangle,
                    callbackSound: playSound
                },
                pins: {
                    number: 24
                }
            });

            const $items = $('.lootbox-items .item');

            function playSound(e) {
                const segmentNumber = wheel.getIndicatedSegmentNumber();
                const $item = $('#item-' + (segmentNumber - 1));

                $items.removeClass('active');
                $item.addClass('active');

                audio.pause();
                audio.currentTime = 0;
                audio.play();
            }

            function resetWheel() {
                wheel.stopAnimation(false);
                wheel.rotationAngle = 0;
                wheel.draw();
            }

            drawTriangle();
            function drawTriangle()  {
                let ctx = wheel.ctx;

                ctx.strokeStyle = '#000';  // Set line colour.
                ctx.fillStyle = '#fff';  // Set fill colour.
                ctx.lineWidth = 3;
                ctx.lineJoin = 'round';
                ctx.beginPath();           // Begin path.
                ctx.moveTo(180, 5);        // Move to initial position.
                ctx.lineTo(220, 5);        // Draw lines to make the shape.
                ctx.lineTo(200, 40);
                ctx.lineTo(181, 5);
                ctx.stroke();              // Complete the path by stroking (draw lines).
                ctx.fill();                // Then fill.
            }

            $('.open-box').click(function (e) {
                const $button = $(this);

                resetWheel();

                $.morpheus.confirm($button.data("confirm"), function (ok) {
                    if (ok) {
                        $button.addClass("disabled");
                        $.getJSON($button.attr('href'), function (data) {
                            if (data.success) {
                                const stop = wheel.getRandomForSegment(data.index + 1);
                                wheel.successMessage = data.message;
                                wheel.animation.stopAngle = stop;
                                wheel.startAnimation();

                                loadPartial('login');
                            } else {
                                $.morpheus.alert(data.message);
                            }

                            $button.removeClass('disabled');
                        });
                    }
                });

                e.preventDefault();
            });
        });
    }
}

window.requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback, element) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

function easeOutSine(t, b, c, d) {
    return c * Math.sin(t/d * (Math.PI/2)) + b;
}

const SpinCase = function(items, wonIndex, complete) {
    const _this = this;

    _this.el = $(".lootbox-case-spinnable");
    _this.position = 0;
    _this.items = items.length;
    _this.itemsWidth = $(".lootbox-case-item").outerWidth(true);
    _this.spinTime = _this.el.data("speed") ?? 5000;
    _this.running = false;
    _this.resultId = wonIndex;
    _this.totalWidth = _this.items * _this.itemsWidth;

    _this.start = function() {
        _this.el.css({
            'transform': 'translateX(0px)'
        });

        const resultOffset = _this.resultId * _this.itemsWidth;
        const loops = 3;
        _this.totalDistance = (loops * _this.totalWidth) + resultOffset;

        _this.running = true;
        _this.startTime = performance.now();

        (function gameLoop(rafTime) {
            _this.update(rafTime);
            if (_this.running) {
                requestAnimFrame(gameLoop);
            }
        })(_this.startTime);
    };

    _this.update = function(rafTime) {
        const deltaTime = rafTime - _this.startTime;
        if (deltaTime >= _this.spinTime) {
            _this.running = false;
            complete();
            return;
        }

        const t = easeOutSine(deltaTime, 0, 1, _this.spinTime);
        _this.position = Math.round(t * _this.totalDistance);
        const translateX = _this.position % _this.totalWidth;

        // if (translateX % _this.itemsWidth <= 5) {
        //     audioWav.currentTime = 0;
        //     audioWav.play();
        // }

        _this.el.css({
            'transform': 'translateX(-' + translateX + 'px)'
        });
    };

    _this.init = function() {
        _this.start();
    };

    _this.init();

    return _this;
};

$(function () {
    createRoulette();
    $(document).on("pjax:end", function() {
        createRoulette();
    });

    $("#btn-open-case").click(function(e) {
        var $this = $(this);

        $.morpheus.confirm($this.data("confirm"), function (ok) {
            if (ok) {
                $.getJSON($this.attr("href"), function (data) {
                    if (data.success) {
                        const spin = new SpinCase(data.items, data.index, function () {
                            $.morpheus.success(data.message);
                        });

                        loadPartial('login');
                    } else {
                        $.morpheus.alert(data.message);
                    }
                });
            }
        });

        e.preventDefault();
    });

});