{% 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>
        <img id="audio-image" src="/static/img/nb.png" alt="JukeBox" style="width="50%"">
        <audio controls autoplay id="audio">
            <source src="{{ url_for('uploaded_file', filename=track.audio_filename) }}">
        </audio>
<style>
        #audio-image {
            width: 20%;
            height: auto;
        }
        /* Additional styles as needed */
    </style>
        </div>
</div>
            <div id="visualizer_wrapper">
                <canvas id='canvas' width="1700" height="350"></canvas>
            </div>

<script>
        const audio = document.getElementById('audio');
        const audioImage = document.getElementById('audio-image');

        audio.addEventListener('play', () => {
            audioImage.src = '/static/img/nb.gif'; // Path to your GIF image
        });

        audio.addEventListener('pause', () => {
            audioImage.src = '/static/img/nb.png'; // Path to your static image
        });

        audio.addEventListener('ended', () => {
            audioImage.src = '/static/img/nb.png'; // Reset to static image when audio ends
        });
    </script>

    <!-- 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>
                        <div class="mb-3">
    <label for="frequencyRange" class="form-label"><p>Frequency Range</p></label>
    <input type="range" class="form-range" id="frequencyRange" min="20" max="20000" value="440" step="10">
    <span id="frequencyValue">440 Hz</span>
</div>
<div class="mb-3">
    <label for="beatThresholdRange" class="form-label"><p>Beat Threshold</p></label>
    <input type="range" class="form-range" id="beatThresholdRange" min="0" max="255" value="128" step="1">
    <span id="thresholdValue">128</span>
</div>
<button type="button" id="normalModeButton" class="btn btn-secondary btn-sm mt-2">Normal Mode</button>
<button type="button" id="beatModeButton" class="btn btn-secondary btn-sm mt-2">Beat Mode</button>
                        <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">
    document.addEventListener("DOMContentLoaded", function() {
        const visualizer = new Visualizer();
        visualizer.ini();

        const sensitivityRange = document.getElementById('sensitivityRange');
        const gapRange = document.getElementById('gapRange');
        const barSizeRange = document.getElementById('barSizeRange');
        const fallingElementsCheck = document.getElementById('fallingElementsCheck');
        const colorPickerTop = document.getElementById('colorPickerTop');
        const colorPickerBottom = document.getElementById('colorPickerBottom');
        const addColorButton = document.getElementById('addColorButton');
        const beatThresholdRange = document.getElementById('beatThresholdRange');
        const frequencyRange = document.getElementById('frequencyRange');
        const frequencyValue = document.getElementById('frequencyValue');
        const thresholdValue = document.getElementById('thresholdValue');
        const normalModeButton = document.getElementById('normalModeButton');
        const beatModeButton = document.getElementById('beatModeButton');

        // Initial display of values
        frequencyValue.textContent = `${frequencyRange.value} Hz`;
        thresholdValue.textContent = `${beatThresholdRange.value}`;

        // Add listeners if the elements exist
        if (sensitivityRange) {
            sensitivityRange.addEventListener('input', function() {
                visualizer.setSensitivity(this.value);
            });
        }

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

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

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

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

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

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

        if (beatThresholdRange) {
            beatThresholdRange.addEventListener('input', function() {
                visualizer.setBeatThreshold(this.value);
                thresholdValue.textContent = this.value;
            });
        }

        if (frequencyRange) {
            frequencyRange.addEventListener('input', function() {
                visualizer.setFrequency(this.value);
                frequencyValue.textContent = `${this.value} Hz`;
            });
        }

        if (normalModeButton) {
            normalModeButton.addEventListener('click', function() {
                visualizer.setMode('normal');
            });
        }

        if (beatModeButton) {
            beatModeButton.addEventListener('click', function() {
                visualizer.setMode('beat');
            });
        }
    });

    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';
        this.colorBottom = '#0000ff';
        this.currentTopColor = this.colorTop;
        this.currentBottomColor = this.colorBottom;
        this.additionalColors = [];
        this.animationId = null;
        this.beatThreshold = 128;
        this.frequency = 440;
        this.mode = 'normal'; // Default mode is 'normal'
    };

    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() {
            const analyser = this.analyser;
            const canvas = document.getElementById('canvas');
            const ctx = canvas.getContext('2d');
            const width = canvas.width;
            const height = canvas.height;
            const meterNum = width / (this.barSize + parseInt(this.gap));
            const capYPositionArray = new Array(meterNum).fill(0);

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

            let colorUpdated = false;

            const draw = () => {
                const array = new Uint8Array(analyser.frequencyBinCount);
                analyser.getByteFrequencyData(array);

                const frequencyIndex = Math.round(this.frequency / (this.audioContext.sampleRate / 2) * array.length);
                const step = Math.round(array.length / meterNum);
                ctx.clearRect(0, 0, width, height);

                let isBeatDetected = false;

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

                    if (!isFinite(value)) continue;

                    if (this.mode === 'beat' && i * step === frequencyIndex && value > this.beatThreshold) {
                        isBeatDetected = true;
                    }

                    var gradient = ctx.createLinearGradient(0, height, 0, height - value);
                    gradient.addColorStop(0, this.currentBottomColor);
                    gradient.addColorStop(1, this.currentTopColor);

                    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);
                    }
                }

                if (this.mode === 'beat' && isBeatDetected && !colorUpdated) {
                    this.updateColorsOnBeat();
                    colorUpdated = true;
                } else if (this.mode === 'beat' && !isBeatDetected) {
                    colorUpdated = false;
                }

                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;
        },
        updateColorsOnBeat: function() {
            if (this.mode !== 'beat') return; // Exit if not in beat mode

            const allColors = [this.colorTop, this.colorBottom, ...this.additionalColors];
            if (Math.random() > 0.5) {
                this.currentTopColor = allColors[Math.floor(Math.random() * allColors.length)];
            } else {
                this.currentBottomColor = allColors[Math.floor(Math.random() * allColors.length)];
            }
        },
        setMode: function(newMode) {
            this.mode = newMode;
            if (newMode === 'normal') {
                this.currentTopColor = this.colorTop;
                this.currentBottomColor = this.colorBottom;
            }
        },
        setBeatThreshold: function(value) {
            this.beatThreshold = value;
        },
        setFrequency: function(value) {
            this.frequency = value;
        }
    };
</script>



        <div class="col-md-8">
            <div class="card-body">
                <h3 class="card-title">{{ track.title }}</h3>
                {% if track.album %}
<div id="sized">
<div class="card">
    <img src="{{ url_for('static', filename='covers/' ~ track.album.cover_filename) }}" class="card-img-top" alt="{{ track.album.title }} cover">
    <div class="card-body">
        <h5 class="card-title">{{ track.album.title }}</h5>
        <p class="card-text">{{ track.album.artist }}</p>
        <a href="{{ url_for('view_album', album_id=track.album.id) }}" class="btn btn-primary">Открыть альбом</a>
    </div>
</div>
</div>
{% else %}
<div class="alert alert-info" role="alert">
    Этот трек не привязан к какому-либо альбому.
</div>
{% 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>
    #sized {
            width:20%;
        }

    * {
    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 %}
make it have button that opens a dropdown where you can see the track info such as bitrate,size in bytes, size in seconds,metadata,type