const legenda = {
    r300: { disabled: "y", label: "Tryb wyjścia AC",  nis: 28, type: "selectList", choice: {0: "SIG", 1: "PAL", 2: "3P1", 3: "3P2", 4: "3P3"}, accuracy: ""},
    r301: { disabled: "n", label: "Priorytet wyjściowy",  nis: 1, type: "selectList", choice: {0: "UTI", 1: "SOL", 2: "SBU", 3: "SUB"}, accuracy: ""},
    r302: { disabled: "n", label: "Zakres napięcia wejściowego",  nis: 2, type: "selectList", choice: {0: "APL", 1: "UPS", 2: "GEN"}, accuracy: ""},
    r303: { disabled: "n", label: "Tryb brzęczyka",  nis: 18, type: "selectList", choice: {0: "nd1", 1: "nd2", 2: "nd3", 3: "nd4"}, accuracy: ""},
    r305: { disabled: "n", label: "Podświetlenie LCD",  nis: 20, type: "selectList", choice: {0: "Wygasza się po 1 minucie", 1: "Zawsze włączone"}, accuracy: ""},
    r306: { disabled: "n", label: "LCD automatycznie powraca do strony głównej",  nis: 19, type: "selectList", choice: {0: "Nie wraca automatycznie", 1: "Powrót po 1 minucie"}, accuracy: ""},
    r307: { disabled: "y", label: "Tryb oszczędzania energii",  nis: 4, type: "selectList", choice: {0: "Wyłączone", 1: "Włączone"}, accuracy: ""},
    r308: { disabled: "y", label: "Automatyczny restart przy przeciążeniu",  nis: 6, type: "selectList", choice: {0: "Wyłączone", 1: "Włączone"}, accuracy: ""},
    r309: { disabled: "y", label: "Automatyczny restart przy przegrzaniu",  nis: 7, type: "selectList", choice: {0: "Wyłączone", 1: "Włączone"}, accuracy: ""},
    r310: { disabled: "y", label: "Automatyczny bypass przy przeciążeniu",  nis: 23, type: "selectList", choice: {0: "Wyłączone", 1: "Włączone"}, accuracy: ""},
    r313: { disabled: "y", label: "EQ baterii",  nis: 33, type: "selectList", choice: {0: "Wyłączone", 1: "Włączone"}, accuracy: ""},
    r320: { disabled: "y", label: "Napięcie wyjściowe", nis: 8, type: "selectListChoice", choice: {2200: "220V", 2300: "230V", 2400:"240V"}, accuracy: "0.1", unit: "V"},
    r321: { disabled: "y", label: "Częstotliwość wyjściowa", nis: 9, type: "selectListChoice", choice: {5000: "50Hz", 6000: "60Hz"}, accuracy: "0.01", unit: "Hz"},
    r323: { disabled: "y", label: "Punkt zabezpieczenia przeciwprzepięciowego akumulatora", nis: 0, type: "selectListUser", accuracy: "0.1", unit: "V"},
    r324: { disabled: "y", label: "Maksymalne napięcie ładowania", nis: 26, type: "selectListUser", accuracy: "0.1", unit: "V"},
    r325: { disabled: "y", label: "Napięcie ładowania pływającego", nis: 27, type: "selectListUser", accuracy: "0.1", unit: "V"},
    r326: { disabled: "y", label: "Punkt przełączenia sieć -> bateria", nis: 13, type: "selectListUser", accuracy: "0.1", unit: "V"},
    r327: { disabled: "y", label: "Punkt przełączenia bateria -> sieć", nis: 12, type: "selectListUser", accuracy: "0.1", unit: "V"},
    r329: { disabled: "y", label: "Punkt wyłączenia odbiorników przy niskim poziomie naładowania baterii i braku zasilania sieciowego", nis: 29, type: "selectListUser", accuracy: "0.1", unit: "V"},
    r331: { disabled: "n", label: "Priorytet ładowania baterii",  nis: 16, type: "selectList", choice: {0: "CSO", 1: "CUT", 2: "SNU", 3: "OSO"}, accuracy: ""},
    r332: { disabled: "y", label: "Maksmalny prąd ładowania PV+Sieć", nis: 2, type: "selectListUser", accuracy: "0.1", unit: "A"},
    r333: { disabled: "n", label: "Moc ładowania sieciowego",  nis: 11, type: "selectListUser", accuracy: "0.1", unit: "A"},
    // r333: { disabled: "n", label: "Moc ładowania sieciowego",  nis: 11, type: "selectListUserChoice", choice: {50: "5A", 100: "10A", 150: "15A", 200: "20A", 250: "25A", 300: "30A", 350: "35A", 400: "40A"}, accuracy: "0.1", unit: "A"},
    r334: { disabled: "y", label: "Napięcie ładowania EQ", nis: 34, type: "selectListUser", accuracy: "0.1", unit: "V"},
    r335: { disabled: "y", label: "Czas EQ", nis: 35, type: "selectListUser", accuracy: "1", unit: "min"},
    r336: { disabled: "y", label: "EQ koniec", nis: 36, type: "selectListUser", accuracy: "1", unit: "min"},
    r337: { disabled: "y", label: "Czas pomiędzy EQ", nis: 37, type: "selectListUser", accuracy: "1", unit: "min"},
    r406: { disabled: "y", label: "", nis: 0, type: "", accuracy: ""},
    r420: { disabled: "y", label: "", nis: 0, type: "", accuracy: ""},

    datetime: { label: "Data i godzina synchronizacji ustawień", unit: "datetime", accuracy: "" }
};

// const legenda = {
//     r301: { label: "Priorytet wyjściowy",  nis: 1, type: "selectList", choice: {0: "UTI", 1: "SOL", 2: "SBU", 3: "SUB"}, accuracy: ""},
//     r302: { label: "Zakres napięcia wejściowego",  nis: 2, type: "selectList", choice: {0: "APL", 1: "UPS", 2: "GEN"}, accuracy: ""},
//     r331: { label: "Priorytet ładowania baterii",  nis: 16, type: "selectList", choice: {0: "CSO", 1: "CUT", 2: "SNU", 2: "OSO"}, accuracy: ""},
//     r333: { label: "Moc ładowania sieciowego",  nis: 16, type: "selectList", choice: {50: "5A", 100: "10A", 150: "15A", 200: "20A", 250: "25A", 300: "30A", 350: "35A", 400: "40A"}, accuracy: "0.1"},


//     datetime: { label: "Data i godzina", unit: "datetime", accuracy: "" }
// };

function createSelect(name, id, choice, selected) {
    let selectHTML = `<select name="${name}" id="${id}">`;

    Object.keys(choice).forEach(key => {
      if (key == selected) {
        selectHTML += `<option value="${key}" selected>${choice[key]}</option>`;
      }else{
        selectHTML += `<option value="${key}">${choice[key]}</option>`;
      }
    });
    
    selectHTML += `</select>`;
    return selectHTML;
}




function getSettings() {
  fetch(
    "api/getSettings.php?key=brt6k11t"
  )
    .then((response) => response.json())
    .then((data) => {
      if (data.success == "yes") {
        console.log(data.settings);
        
        let tableHTML = '';
        
        // Konwertuj obiekt na tablicę wartości
        const settingsArray = Object.values(data.settings);
        
        // Iteruj po tablicy
        settingsArray.forEach((setting, index) => {
          if(setting.name == "id") return;
          // Sprawdź czy rejestr istnieje w legendzie
          if(!legenda[setting.name]) {
            console.warn(`Rejestr ${setting.name} nie istnieje w legendzie`);
            return;
          }
          console.log(setting.name);
          console.log(document.getElementById(setting.name)); // Teraz będzie działać
            const btnStatus = legenda[setting.name].disabled === "y" ? "disabled" : "";

            if(legenda[setting.name].type == "selectList") {
                const selectHTML = createSelect(setting.name, setting.name, legenda[setting.name].choice, setting.value);

                tableHTML += `<tr>
                    <td>${legenda[setting.name].label} (Ust. ${legenda[setting.name].nis})</td>
                    <td>${legenda[setting.name].choice[setting.value]}</td>
                    <td>${selectHTML}</td>
                    <td><button ${btnStatus} onclick="saveSetting('${setting.name}')">Zapisz</button></td>
                </tr>`;
            } else if(legenda[setting.name].type == "selectListChoice") {
                const selectHTML = createSelect(setting.name, setting.name, legenda[setting.name].choice, setting.value);
                tableHTML += `<tr>
                    <td>${legenda[setting.name].label} (Ust. ${legenda[setting.name].nis})</td>
                    <td>${(setting.value * legenda[setting.name].accuracy).toFixed(1)} ${legenda[setting.name].unit}</td>
                    <td>${selectHTML}</td>
                    <td><button ${btnStatus} onclick="saveSetting('${setting.name}')">Zapisz</button></td>
                </tr>`;
              } else if(legenda[setting.name].type == "selectListUser") {
                tableHTML += `<tr>
                    <td>${legenda[setting.name].label} (Ust. ${legenda[setting.name].nis})</td>
                    <td>${(setting.value * legenda[setting.name].accuracy).toFixed(1)} ${legenda[setting.name].unit}</td>
                    <td>${setting.value}</td>
                    <td><button ${btnStatus} onclick="saveSetting('${setting.name}')">Zapisz</button></td>
                </tr>`;
            } else if(setting.name == "datetime") {
                tableHTML += `<tr>
                    <td>${legenda[setting.name].label}</td>
                    <td colspan="3">${setting.value}</td>
                </tr>`;
            } else {
                tableHTML += `<tr>
                    <td>${legenda[setting.name].label} (Ust. ${legenda[setting.name].nis})</td>
                    <td>${setting.value} ${legenda[setting.name].unit ? legenda[setting.name].unit : ''}</td>
                    <td>${setting.value}</td>
                    <td><button ${btnStatus} onclick="saveSetting('${setting.name}')">Zapisz</button></td>
                </tr>`;
            }
        });
        
        document.getElementById('settingsTableBody').innerHTML = tableHTML;
        
      } else if (data.success == "no") {
        console.error("Błąd: " + data.message);
      }
    })
    .catch((error) => {
      console.error("Wystąpił błąd podczas pobierania danych:", error);
    });
}

getSettings();

function saveSetting(register) {
    const value = document.getElementById(register).value;
    console.log(register);
    
    fetch('api/saveSettings.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `key=brt6k11t&register=${register}&value=${value}`
    })
    .then(response => response.json())
    .then(data => {
        if(data.success == 'yes') {
            // Pokaż modal i uruchom odliczanie
            document.getElementById('saveModal').style.display = 'flex';
            
            let countdown = 5;
            document.getElementById('countdown').textContent = countdown;
            
            const interval = setInterval(() => {
                countdown--;
                document.getElementById('countdown').textContent = countdown;
                
                if (countdown <= 0) {
                    clearInterval(interval);
                    // location.reload(); // Odśwież stronę
                    getSettings(); // Pobierz ustawienia ponownie
                    document.getElementById('saveModal').style.display = 'none';
                }
            }, 1000);
        } else {
            // Ukryj modal i pokaż błąd
            // clearInterval(interval);
            document.getElementById('saveModal').style.display = 'none';
            alert('Błąd: ' + data.message);
        }
    })
    .catch(error => {
        // Ukryj modal w przypadku błędu
        clearInterval(interval);
        document.getElementById('saveModal').style.display = 'none';
        alert('Wystąpił błąd podczas zapisywania');
    });
}