// JavaScript for page navigation
const page1Link = document.getElementById('page1-link');
const page2Link = document.getElementById('page2-link');
const page1 = document.getElementById('page1');
const page2 = document.getElementById('page2');

page1Link.addEventListener('click', () => {
    page1.classList.add('active');
    page2.classList.remove('active');
});

page2Link.addEventListener('click', () => {
    page2.classList.add('active');
    page1.classList.remove('active');
});

const uploadButton = document.getElementById('upload-button');
const firmwareFile = document.getElementById('firmware-file');
const uploadForm = document.getElementById('upload-form');
const dropZone = document.getElementById('drop-zone');
const progressBar = document.getElementById('upload-progress');

// 点击拖放区域触发文件选择
dropZone.addEventListener('click', () => {
    firmwareFile.click();
});

// 文件拖入拖放区域
['dragenter', 'dragover'].forEach(eventName => {
    dropZone.addEventListener(eventName, (e) => {
        e.preventDefault();
        e.stopPropagation();
        dropZone.classList.add('highlight');
    });
});

// 文件拖离拖放区域
['dragleave', 'drop'].forEach(eventName => {
    dropZone.addEventListener(eventName, (e) => {
        e.preventDefault();
        e.stopPropagation();
        dropZone.classList.remove('highlight');
    });
});

// 文件放入拖放区域
dropZone.addEventListener('drop', (e) => {
    const files = e.dataTransfer.files;
    if (files.length) {
        firmwareFile.files = files;
        dropZone.textContent = files[0].name; // 更新文本内容为文件名
    }
});

// 更新文本内容为文件名
firmwareFile.addEventListener('change', () => {
    if (firmwareFile.files.length) {
        dropZone.textContent = firmwareFile.files[0].name;
    }
});

// 上传文件并显示进度
uploadButton.addEventListener('click', () => {
    const file = firmwareFile.files[0];
    if (!file) {
        alert('请选择一个文件！');
        return;
    }

    const formData = new FormData();
    formData.append('update', file);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/update', true);

    xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            progressBar.value = percentComplete;
        }
    };

    xhr.onload = function () {
        if (xhr.status === 200) {
            alert('上传成功！');
        } else {
            alert('上传失败，请重试。');
        }
        progressBar.value = 0;
    };

    xhr.onerror = function () {
        alert('上传过程中发生错误。错误码：' + xhr.status);
        progressBar.value = 0;
    };

    xhr.timeout = 100000; // 设置超时时间为100秒
    xhr.ontimeout = function () {
        alert('服务器无响应，页面将刷新。');
        location.reload();
    };

    xhr.send(formData);
});


var history_data = [
    {voltageHistory: [], currentHistory: [], powerHistory: []},
    {voltageHistory: [], currentHistory: [], powerHistory: []},
    {voltageHistory: [], currentHistory: [], powerHistory: []},
    {voltageHistory: [], currentHistory: [], powerHistory: []},
    {voltageHistory: [], currentHistory: [], powerHistory: []},
    {voltageHistory: [], currentHistory: [], powerHistory: []},
    {voltageHistory: [], currentHistory: [], powerHistory: []},
    {voltageHistory: [], currentHistory: [], powerHistory: []},
    {voltageHistory: [], currentHistory: [], powerHistory: []},
    {voltageHistory: [], currentHistory: [], powerHistory: []}
];


function addToHistory(index, voltage, current, power) {
    history_data[index].voltageHistory.push(voltage);
    history_data[index].currentHistory.push(current);
    history_data[index].powerHistory.push(power);

    history_data[index].voltageHistory = history_data[index].voltageHistory.slice(-500);
    history_data[index].currentHistory = history_data[index].currentHistory.slice(-500);
    history_data[index].powerHistory = history_data[index].powerHistory.slice(-500);
}

function updateStatus() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/status', true);

    xhr.onload = function () {
        const cards = document.querySelectorAll('.status-card');

        if (xhr.status === 200) {
            var data = JSON.parse(xhr.responseText);
            data = data.data;
            const buffer = new ArrayBuffer(4);
            const view = new DataView(buffer);
            view.setFloat32(0, data[50], true);
            var alert_tmp = new Uint8Array(buffer);
            var index_convert = [8,9,0,1,2,3,4,5,6,7];
            cards.forEach((card, index) => {
                const voltage = card.querySelector('.voltage');
                const current = card.querySelector('.current');
                const power = card.querySelector('.power');
                const alert = card.querySelector('.alert');
                const canvas = card.querySelector('.chart');

                // Update text content
                voltage.textContent = data[index_convert[index]*2].toFixed(2);
                current.textContent = data[index_convert[index]*2+1].toFixed(2);
                power.textContent = data[index_convert[index]*3+20].toFixed(2);
                // alert.textContent = data[index*2].alert;

                addToHistory(index_convert[index], data[index_convert[index]*2], data[index_convert[index]*2+1], data[index_convert[index]*3+20]);

                // Draw chart
                drawChart(canvas, history_data[index_convert[index]]);
            });
        } else {
            console.error('Failed to fetch status data');

            cards.forEach((card) => {
                const voltage = card.querySelector('.voltage');
                const current = card.querySelector('.current');
                const power = card.querySelector('.power');
                const canvas = card.querySelector('.chart');

                // Display NaN for text content
                voltage.textContent = 'NaN';
                current.textContent = 'NaN';
                power.textContent = 'NaN';

                addToHistory(index, 0, 0, 0);

                // Draw chart with 0 values
                drawChart(canvas, history_data[index]);
            });
        }
    };

    xhr.onerror = function () {
        console.error('Error during status update request');

        const cards = document.querySelectorAll('.status-card');
        cards.forEach((card) => {
            const voltage = card.querySelector('.voltage');
            const current = card.querySelector('.current');
            const power = card.querySelector('.power');
            const canvas = card.querySelector('.chart');

            // Display NaN for text content
            voltage.textContent = 'NaN';
            current.textContent = 'NaN';
            power.textContent = 'NaN';

            addToHistory(index, 0, 0, 0);
            // Draw chart with 0 values
            drawChart(canvas, history_data[index]);
        });
    };

    xhr.send();
}

function drawChart(canvas, data) {
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 获取历史数据
    const voltageData = data.voltageHistory || [0, 0, 0, 0, 0];
    const currentData = data.currentHistory || [0, 0, 0, 0, 0];
    const powerData = data.powerHistory || [0, 0, 0, 0, 0];

    const allData = [...voltageData, ...currentData, ...powerData];
    const maxValue = Math.max(...allData);
    const minValue = Math.min(...allData);

    const colors = {
        voltage: 'blue',
        current: 'green',
        power: 'orange'
    };

    const maxPoints = voltageData.length;
    const width = canvas.width;
    const height = canvas.height;
    const stepX = width / (maxPoints - 1);

    function drawLine(data, color) {
        ctx.beginPath();
        ctx.strokeStyle = color;
        ctx.lineWidth = 2;
        data.forEach((value, index) => {
            const x = index * stepX;
            const y = height - ((value - minValue) / (maxValue - minValue)) * height; // 自动缩放
            if (index === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        });
        ctx.stroke();
    }

    drawLine(voltageData, colors.voltage);
    drawLine(currentData, colors.current);
    drawLine(powerData, colors.power);
}

setInterval(updateStatus, 500);

const toggleSidebarButton = document.getElementById('toggle-sidebar');
const sidebar = document.querySelectorAll('.sidebar');
const sideButtonContainer = document.getElementById('side-button');

toggleSidebarButton.addEventListener('click', () => {
    for(let i = 0; i < sidebar.length; i++) {
        sidebar[i].classList.toggle('hidden');
    }
    sideButtonContainer.classList.toggle('hide-arrow');
    sideButtonContainer.classList.toggle('show-arrow');
});