{% 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">Visualizer Settings</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">Sensitivity</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">Bar Size</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">Gap Between Bars</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="fallingElementsCheck" class="form-check-label">Falling Elements</label>
                            <input type="checkbox" class="form-check-input" id="fallingElementsCheck" checked>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</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);
        });
    };

    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.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);
                    var red = (value / 255) * 255;
                    var green = 255 - red;

                    ctx.fillStyle = `rgb(${red},${green},0)`;
                    ctx.fillRect(i * (this.barSize + parseInt(this.gap)), height - value, this.barSize, height);

                    if (this.fallingElements) {
                        // Draw the falling cap
                        if (value < capYPositionArray[i]) {
                            // Cap falls with a bounce effect
                            capYPositionArray[i] -= 2; // Lower it more gradually
                            if (capYPositionArray[i] < value) {
                                capYPositionArray[i] = value; // Reset cap if it falls below current height
                            }
                        } else {
                            capYPositionArray[i] = value;
                        }
                        // Draw the cap
                        ctx.fillStyle = '';
                        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;
        }
    };
    </script>

    </div>


        <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 %}
add color select in the modal for the visualiser