{% extends 'audiobase.html' %}

{% block title %}{{ track.title }}{% endblock %}

{% block content %}
<div class="card mb-4">
    <div class="row g-0">
        <div class="col-md-4">
        <div class="player">
        <div class="imgbx">
            <img src="{{ url_for('static', filename='covers/' + track.cover_filename) }}">
        </div>
        <audio controls autoplay>
            <source src="{{ url_for('uploaded_file', filename=track.audio_filename) }}">
        </audio>
        </div>
</div>
            <div id="visualizer_wrapper">
                <canvas id='canvas' width="1700" height="350"></canvas>
            </div>



    <!-- Settings Modal -->
    <div class="modal fade" id="settingsModal" tabindex="-1" aria-labelledby="settingsModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="settingsModalLabel"><p>Visualizer Settings</p></p></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="sensitivityRange" class="form-label"><p>Sensitivity</p></label>
                            <input type="range" class="form-range" id="sensitivityRange" min="0.1" max="100" value="50" step="0.1">
                        </div>
                        <div class="mb-3">
                            <label for="barSizeRange" class="form-label"><p>Bar Size</p></label>
                            <input type="range" class="form-range" id="barSizeRange" min="0.1" max="10" value="1" step="0.1">
                        </div>
                        <div class="mb-3">
                            <label for="gapRange" class="form-label"><p>Gap Between Bars</p></label>
                            <input type="range" class="form-range" id="gapRange" min="0.1" max="10" value="0" step="0.1">
                        </div>
                        <div class="mb-3">
                            <label for="colorPickerTop" class="form-label"><p>Top Bar Color</p></label>
                            <input type="color" id="colorPickerTop" value="#ff0000">
                        </div>
                        <div class="mb-3">
                            <label for="colorPickerBottom" class="form-label"><p>Bottom Bar Color</p></label>
                            <input type="color" id="colorPickerBottom" value="#0000ff">
                        </div>
                        <div id="additionalColors"></div>
                        <button type="button" id="addColorButton" class="btn btn-primary btn-sm mt-2"><p>Add More Colors</p></button>
                    </div>             <div class="mb-3">
                            <label for="fallingElementsCheck" class="form-check-label"><p>Falling Elements</p></label>
                            <input type="checkbox" class="form-check-input" id="fallingElementsCheck" checked>
                        </div>
                        <button type="button" class="btn btn-secondary btn-sm mt-2" data-bs-dismiss="modal"><p>Close</p></button>
                    </div>



                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript for Visualizer -->
    <script type="text/javascript">
    window.onload = function() {
        const visualizer = new Visualizer();
        visualizer.ini();

        // Event listeners for settings
        document.getElementById('sensitivityRange').addEventListener('input', function() {
            visualizer.setSensitivity(this.value);
        });

        document.getElementById('gapRange').addEventListener('input', function() {
            visualizer.setGap(this.value);
        });

        document.getElementById('barSizeRange').addEventListener('input', function() {
            visualizer.setBarSize(this.value);
        });

        document.getElementById('fallingElementsCheck').addEventListener('change', function() {
            visualizer.setFallingElements(this.checked);
        });

        document.getElementById('colorPickerTop').addEventListener('input', function() {
            visualizer.setColorTop(this.value);
        });

        document.getElementById('colorPickerBottom').addEventListener('input', function() {
            visualizer.setColorBottom(this.value);
        });

        document.getElementById('addColorButton').addEventListener('click', function() {
            visualizer.addColor();
        });
    };

    var Visualizer = function() {
        this.audioElement = document.querySelector('audio');
        this.audioContext = null;
        this.source = null;
        this.analyser = null;
        this.sensitivity = 50;
        this.gap = 0;
        this.barSize = 1;
        this.fallingElements = true;
        this.colorTop = '#ff0000'; // Default top color
        this.colorBottom = '#0000ff'; // Default bottom color
        this.additionalColors = [];
        this.animationId = null;
    };

    Visualizer.prototype = {
        ini: function() {
            this._prepareAPI();
            this._start();
        },
        _prepareAPI: function() {
            window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
            window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame;
            window.cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.msCancelAnimationFrame;
            try {
                this.audioContext = new AudioContext();
            } catch (e) {
                console.error('Your browser does not support AudioContext');
            }
        },
        _start: function() {
            if (this.audioContext) {
                this.source = this.audioContext.createMediaElementSource(this.audioElement);
                this.analyser = this.audioContext.createAnalyser();
                this.source.connect(this.analyser);
                this.analyser.connect(this.audioContext.destination);
                this._drawSpectrum();
            }
        },
        _drawSpectrum: function() {
            var analyser = this.analyser;
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext('2d');
            var width = canvas.width;
            var height = canvas.height;
            var meterNum = width / (this.barSize + parseInt(this.gap));
            var capYPositionArray = new Array(meterNum).fill(0);

            ctx.clearRect(0, 0, width, height);

            const draw = () => {
                var array = new Uint8Array(analyser.frequencyBinCount);
                analyser.getByteFrequencyData(array);
                var step = Math.round(array.length / meterNum);
                ctx.clearRect(0, 0, width, height);

                for (var i = 0; i < meterNum; i++) {
                    var value = array[i * step] * (this.sensitivity / 50);

                    // Ensure value is a finite number
                    if (!isFinite(value)) {
                        value = 0; // or some default value
                    }

                    var percentage = value / 255;
                    var colorIndex = i % (this.additionalColors.length + 1);

                    var topColor, bottomColor;
                    if (colorIndex === 0) {
                        topColor = this.colorTop;
                        bottomColor = this.colorBottom;
                    } else {
                        topColor = bottomColor = this.additionalColors[colorIndex - 1];
                    }

                    // Ensure gradient values are finite numbers
                    var gradient = ctx.createLinearGradient(0, height, 0, height - value);
                    gradient.addColorStop(0, bottomColor);
                    gradient.addColorStop(1, topColor);

                    ctx.fillStyle = gradient;
                    ctx.fillRect(i * (this.barSize + parseInt(this.gap)), height - value, this.barSize, height);

                    if (this.fallingElements) {
                        if (value < capYPositionArray[i]) {
                            capYPositionArray[i] -= 2;
                            if (capYPositionArray[i] < value) {
                                capYPositionArray[i] = value;
                            }
                        } else {
                            capYPositionArray[i] = value;
                        }
                        ctx.fillRect(i * (this.barSize + parseInt(this.gap)), height - capYPositionArray[i] - 2, this.barSize, 2);
                    }
                }
                this.animationId = requestAnimationFrame(draw);
            };
            this.animationId = requestAnimationFrame(draw);
        },
        setSensitivity: function(value) {
            this.sensitivity = value;
        },
        setGap: function(value) {
            this.gap = value;
        },
        setBarSize: function(value) {
            this.barSize = value;
        },
        setFallingElements: function(enabled) {
            this.fallingElements = enabled;
        },
        setColorTop: function(value) {
            this.colorTop = value;
        },
        setColorBottom: function(value) {
            this.colorBottom = value;
        },
        addColor: function() {
            const colorId = `colorPickerAdditional${this.additionalColors.length}`;
            const container = document.getElementById('additionalColors');
            const label = document.createElement('label');
            label.className = 'form-label';
            label.innerText = `Additional Color ${this.additionalColors.length + 1}`;
            const input = document.createElement('input');
            input.type = 'color';
            input.id = colorId;
            input.value = '#ffffff';
            input.addEventListener('input', (e) => this.setAdditionalColor(this.additionalColors.length, e.target.value));

            container.appendChild(label);
            container.appendChild(input);
            container.appendChild(document.createElement('br'));
            this.additionalColors.push('#ffffff');
        },
        setAdditionalColor: function(index, value) {
            this.additionalColors[index] = value;
        }
    };
    </script>



        <div class="col-md-8">
            <div class="card-body">
                <h3 class="card-title">{{ track.title }}</h3>
                {% if track.album_obj %}
                <p class="card-text"><strong>Альбом:</strong> {{ track.album_obj.title }} - {{ track.album_obj.artist }}</p>
                {% endif %}
                <p class="card-text"><strong>Лайки:</strong> {{ track.likes }}</p>


                {% if not liked %}
                <form action="{{ url_for('like', track_id=track.id) }}" method="post">
                    <button type="submit" class="btn btn-success">Лайк</button>
                </form>
                {% else %}
                <p class="text-success">Вы уже лайкнули этот трек.</p>
                {% endif %}


                <form action="{{ url_for('delete_track', track_id=track.id) }}" method="post" onsubmit="return confirm('Вы уверены, что хотите удалить этот трек?');">
                    <button type="submit" class="btn btn-danger mt-2">Удалить Трек</button>
                </form>
                <button type="button" class="btn btn-success btn-sm mt-2" data-bs-toggle="modal" data-bs-target="#settingsModal">
            Settings
        </button>

    <style>
    * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
audio::-webkit-media-controls-enclosure {
    border-radius: 0;
}
.player {
    position: relative;
    width: 350px;
    background: #f1f3f4;
    box-shadow: 0 50px 80px rgba(0, 0, 0, 0.25);
}

.player .imgbx {
    position: relative;
    width: 100%;
    height: 350px;
}

.player .imgbx img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.player audio {
    width: 100%;
    outline: none;
}
</style>
            </div>
        </div>
    </div>
</div>
{% endblock %}
every added color should be used as one of the main colors randomly one of them every beat