  <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>

  
    <script>
      const messages = []; // Array om berichten op te slaan

// DOM element to display messages
const messageContainer = document.getElementById('messages');

var brokerUrl;
var options;

brokerUrl = "wss://mqtt.p2000.quassi.nl:19002"; // WebSocket URL for Mosquitto

options = {
    username: "p2000",         // MQTT username
    password: "p2000",         // MQTT password
    keepalive: 60,             // Keep alive interval in seconds
    reconnectPeriod: 1000,     // Reconnection interval in ms
    rejectUnauthorized: false, // Alleen voor tests; schakel dit uit in productie
    clientId: `mqtt_${Math.random().toString(16).substr(2, 8)}` // Unique client ID
};

// Create MQTT client and connect
const client = mqtt.connect(brokerUrl, options);


// --------------------------------
// ---- Event: Successful connection
// --------------------------------
client.on('connect', () => {
    document.getElementById('status').textContent = "P2K-server connected";
    console.log("Connected to MQTT broker");

    // Subscribe to the Server topic
    //const topic = "P2000/+/#";
    //const topics = ['P2000/Server', 'P2000/+/Brandweer', 'P2000/+/Ambulance', 'P2000/+/Politie', 'P2000/+/Test', 'P2000/+/Onbekend'];
    const topics = ['P2000/Server/#'];
    topics.forEach(topic => {
      client.subscribe(topic, (err) => {
          if (err) {
              console.error(`Failed to subscribe to topic: ${topic}`, err);
          } else {
              console.log(`Subscribed to topic: ${topic}`);
          }
      });
    });

    // Subscribe to the default topics
    DisciplineSubscribeUnsubscribe();

});

// --------------------------------
// ---- Event: Receive message
// --------------------------------
client.on('message', (topic, message) => {
  //console.log(`Message received on topic ${topic}: ${message.toString()}`);  
 
  if (message.length > 0 )
  {

    if (sound)
    {
      var x = document.getElementById("p2000Sound"); 
      x.play();
    }

    var json;

    try {
      json = JSON.parse(message.toString());
      
      // Voeg bericht toe aan de array
      messages.push(json);
      
      // Sorteer de berichten op basis van datum en tijd
      messages.sort((a, b) => {
          const dateA = new Date(`${formatDate(a.Date, a.Time)}`);
          const dateB = new Date(`${formatDate(b.Date, b.Time)}`);
          return dateB - dateA; // Aflopende volgorde
      });
      document.getElementById('count').textContent = messages.length + ` (${messages[0].Time.split(":").slice(0, 2).join(":")} - ${messages[messages.length-1].Time.split(":").slice(0, 2).join(":")})`;
      
      // Leeg de container
      messageContainer.innerHTML = '';
      
      // Voeg gesorteerde berichten toe aan de UI
      messages.slice(0, 20).forEach(msg => {
      //messages.forEach(msg => {
          const msgDiv = document.createElement('div');
          msgDiv.classList.add('message');
          msgDiv.innerHTML = `
            <div class="relative mx-auto my-6 bg-gray-700 shadow-sm border border-slate-200 rounded-lg">
              <div class="flex justify-between items-center text-gray-700 p-2">
                <div class="pl-2 w-20 h-6 bg-${msg.Colour}-500 rounded-sm flex items-center justify-center text-white text-sm">
                  ${msg.Time.split(":").slice(0, 2).join(":")}
                </div>
                <span class="text-sm text-slate-100">
                  ${formatDateString(msg.Date)}
                </span>
              </div>
              <div class="mx-3 mb-0 border-b border-slate-200 pt-3 pb-2 px-1">
                <h5 class="mb-2 text-slate-200 text-xl font-semibold">
                  ${msg.MessageText}
                </h5>
              </div>
              <div class="p-4">
                ${msg.Capcodes.map(capcode => `
                  <p class="text-slate-300 leading-normal font-light">
                    <span class="inline-block w-2 h-2 bg-${capcode.Colour}-500 mr-2"></span>  
                    ${capcode.CapcodeNr} - ${capcode.Omschrijving} ${capcode.Plaats ? `(<i>${capcode.Plaats}</i>)` : ""}
                  </p>
                `).join('')}
              </div>
              <div class="flex justify-between items-center text-gray-700 p-1">
                <div></div>
                <span class="text-xs text-slate-500">${msg.Topic}</span>
              </div>
            </div>
          `;
          messageContainer.appendChild(msgDiv); // Voeg gesorteerde berichten toe
      });
      
    } catch (error) {
      console.error("Fout bij het parsen van JSON:", error.message);
      console.error("Foutieve JSON-string:", message.toString());
    }
  }
  else
  {
    // Dit zijn de clean-up berichten 0 byte
    //console.error(`Message received on topic ${topic}; Length = : ${message.length}`);  
  }

  
});


// --------------------------------
// ---- Event: Connection error
// --------------------------------
client.on('error', (err) => {
    document.getElementById('status').textContent = "Connection Error!";
    console.error("Connection error:", err);
});


// --------------------------------
// ---- Event: Disconnected
// --------------------------------
client.on('close', () => {
    document.getElementById('status').textContent = "Disconnected.";
    console.log("Disconnected from MQTT broker");
});


// ---- Function: Format P2000 date and time
function formatDate(dateString, timeString) {
  const [day, month, year] = dateString.split('-');
  
  return new Date(`20${year}-${month}-${day}T${timeString}`);
}

// ---- Function: Leest de waarde van de Discipline checkboxs en een MQTT subscribe/unsubscribe aanroep doet
function DisciplineSubscribeUnsubscribe() {
  messages.length = 0;
  messageContainer.innerHTML = '';

  const regios = ['Groningen', 'Friesland', 'Drenthe', 'IJsselland', 'Twente', 'Noord- en Oost-Gelderland', 'Gelderland-Midden', 'Gelderland-Zuid', 'Utrecht', 'Noord-Holland Noord', 'Zaanstreek-Waterland', 'Kennemerland', 'Amsterdam-Amstelland', 'Gooi en Vechtstreek', 'Haaglanden', 'Hollands-Midden', 'Rotterdam-Rijnmond', 'Zuid-Holland Zuid', 'Zeeland', 'Midden- en West-Brabant', 'Brabant-Noord', 'Brabant-Zuidoost', 'Limburg-Noord', 'Limburg-Zuid', 'Flevoland'];
  const disc = ['Brandweer', 'Ambulance', 'Politie', 'MMT', 'KNRM', 'Bruggen', 'Test', 'Onbekend'];

  // Unsubscribe all disciplines
  regios.forEach(r => {
    disc.forEach(d => {
      const topic = "P2000/"+ r + "/" + d + "/#";

      // MQTT unsubscribe
      client.unsubscribe(topic, (err) => {
        if (err) {
          console.error(`Failed to unsubscribe to topic: ${topic}`, err);
        } else {
          //console.log(`Unsubscribed to topic: ${topic}`);
        }
      });
    });
  });

  // Subscribe only selected disciplines
  regios.forEach(r => {
    var regioID = 'regio_' + r.replace(/ /g, '_');
    //console.log(regioID);
    const isCheckedR = document.getElementById(regioID).checked;
    

    disc.forEach(d => {
      var discID = 'discipline_' + d;
    //console.log(discID);
      const isCheckedD = document.getElementById(discID).checked;
      const topic = "P2000/"+ r + "/" + d + "/#";

      if (isCheckedD && isCheckedR) {
        // MQTT subscribe
        client.subscribe(topic, (err) => {
          if (err) {
            console.error(`Failed to subscribe to topic: ${topic}`, err);
          } else {
            //console.log(`Subscribed to topic: ${topic}`);
          }
        });
      } else {
        //
      }
    });
  });
}

  // Functie om de datum om te zetten naar het gewenste formaat
  function formatDateString(dateString) {
    const months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
    
    // Split de string in dag, maand en jaar
    const parts = dateString.split('-');
    const day = parts[0];  // Dag
    const month = parts[1];  // Maand (nummer)
    const year = parts[2];  // Jaar (afgekort)

    // Haal de maand afkorting op
    const monthName = months[parseInt(month) - 1];
  
    // Maak de nieuwe string
    return `${day}${monthName}${year}`;
  }



      // Initial status of the sound
      let sound = false;

      // Function to toggle the sound variable and update the button's style
      function toggleSound() {
          sound = !sound;
          updateButtonStyles();
      }



    // Function to update the button's style based on the sound variable
    function updateButtonStyles() {
      console.log(sound);
      
      const buttonS = document.getElementById('soundButton');
      if (sound) {
          buttonS.classList.remove('bg-gray-500');
          buttonS.classList.add('bg-green-500');
      } else {
          buttonS.classList.remove('bg-green-500');
          buttonS.classList.add('bg-gray-500');
      }


    }

    // Ensure the buttons have the correct style on page load
    window.onload = updateButtonStyles;

    // Discipline: JavaScript om de overlay in te schakelen en instellingen op te slaan
    const openSettingsButtonD = document.getElementById('openSettingsDisciplines');
    const overlayD = document.getElementById('overlayDisciplines');
    const closeOverlayButtonD = document.getElementById('closeOverlayD');
    const saveSettingsButtonD = document.getElementById('saveSettingsD');

    openSettingsButtonD.addEventListener('click', () => {
      overlayD.classList.remove('hidden');
    });

    closeOverlayButtonD.addEventListener('click', () => {
      overlayD.classList.add('hidden');
    });

    saveSettingsButtonD.addEventListener('click', () => {
      DisciplineSubscribeUnsubscribe();

      // Voorbeeld: log de instellingen naar de console
      console.log("Instellingen opgeslagen");
      
      // Sluit de overlayD na het opslaan
      overlayD.classList.add('hidden');
    });


    // Regios: JavaScript om de overlay in te schakelen en instellingen op te slaan
    const openSettingsButtonR = document.getElementById('openSettingsRegios');
    const overlayR = document.getElementById('overlayRegios');
    const closeOverlayButtonR = document.getElementById('closeOverlayR');
    const saveSettingsButtonR = document.getElementById('saveSettingsR');

    openSettingsButtonR.addEventListener('click', () => {
      overlayR.classList.remove('hidden');
    });

    closeOverlayButtonR.addEventListener('click', () => {
      overlayR.classList.add('hidden');
    });

    saveSettingsButtonR.addEventListener('click', () => {
      DisciplineSubscribeUnsubscribe();

      // Voorbeeld: log de instellingen naar de console
      console.log("Instellingen opgeslagen");
      
      // Sluit de overlayR na het opslaan
      overlayR.classList.add('hidden');
    });