// =========================
// LOGIN CHECK
// =========================

if(localStorage.getItem("isLogin") !== "true"){

    window.location.href =
    "login.html";

}

// =========================
// USERNAME
// =========================

const username =
localStorage.getItem("username");

// =========================
// LOGOUT
// =========================

function logout(){

    localStorage.removeItem("isLogin");

    localStorage.removeItem("username");

    window.location.href =
    "login.html";

}
/* =========================
FINAL MQTT REALTIME
SMART AQUARIUM
========================= */

console.log("SCRIPT LOADED");

/* =========================
ELEMENT
========================= */

const phValue =
document.getElementById("ph-value");

const turbidityValue =
document.getElementById("turbidity-value");

const tempValue =
document.getElementById("temp-value");

const phStatus =
document.getElementById("ph-status");

const turbidityStatus =
document.getElementById("turbidity-status");

const tempStatus =
document.getElementById("temp-status");

const ledPh =
document.getElementById("led-ph");

const ledTemp =
document.getElementById("led-temp");

const ledPhStatus =
document.getElementById("led-ph-status");

const ledTempStatus =
document.getElementById("led-temp-status");

const pumpOut =
document.getElementById("pump-out");

const pumpIn =
document.getElementById("pump-in");

const historyBody =
document.getElementById("history-body");

const mqttStatus =
document.getElementById("mqtt-status");

/* =========================
MQTT
========================= */

const broker =
"wss://elevenicict.cloud.shiftr.io:443/mqtt";

const client =
mqtt.connect(broker, {

    username: "elevenicict",
    password: "8oWIeiFxydoQcexD"

});

/* =========================
LATEST DATA
========================= */

let latestData = {

    ph: 7,
    temp: 27,
    turbidity: "CLEAR WATER",

    ledph: "OFF",
    ledtemp: "OFF",

    pumpout: "OFF",
    pumpin: "OFF"

};

/* =========================
MQTT CONNECT
========================= */

client.on("connect", () => {

    console.log("MQTT CONNECTED");

    mqttStatus.innerHTML =
    "MQTT Connected";

    mqttStatus.className =
    "mqtt-status connected";

    /* SUBSCRIBE */

    client.subscribe("aquarium/ph");

    client.subscribe("aquarium/temp");

    client.subscribe("aquarium/status");

    client.subscribe("aquarium/turbidity");

    client.subscribe("aquarium/ledph");

    client.subscribe("aquarium/ledtemp");

    client.subscribe("aquarium/pumpoutstatus");

    client.subscribe("aquarium/pumpinstatus");

    updateUI();

});

/* =========================
MQTT RECONNECT
========================= */

client.on("reconnect", () => {

    console.log("RECONNECTING MQTT...");

    mqttStatus.innerHTML =
    "MQTT Reconnecting...";

    mqttStatus.className =
    "mqtt-status reconnect";

});

/* =========================
MQTT OFFLINE
========================= */

client.on("offline", () => {

    console.log("MQTT OFFLINE");

    mqttStatus.innerHTML =
    "MQTT Offline";

    mqttStatus.className =
    "mqtt-status offline";

});

/* =========================
MQTT ERROR
========================= */

client.on("error", (err) => {

    console.log("MQTT ERROR:", err);

    mqttStatus.innerHTML =
    "MQTT Error";

    mqttStatus.className =
    "mqtt-status offline";

});

/* =========================
MQTT RECEIVE
========================= */

client.on("message", (topic, message) => {

    const data =
    message.toString();

    console.log(topic, data);

    /* =========================
    PH
    ========================= */

    if(topic === "aquarium/ph"){

        latestData.ph =
        parseFloat(data);

    }

    /* =========================
    TEMP
    ========================= */

    if(topic === "aquarium/temp"){

        latestData.temp =
        parseFloat(data);

    }

    /* =========================
    TURBIDITY
    ========================= */

    if(topic === "aquarium/turbidity"){

        latestData.turbidity =
        data;

    }

    /* =========================
    LED PH
    ========================= */

    if(topic === "aquarium/ledph"){

        latestData.ledph =
        data;

    }

    /* =========================
    LED TEMP
    ========================= */

    if(topic === "aquarium/ledtemp"){

        latestData.ledtemp =
        data;

    }

    /* =========================
    PUMP OUT
    ========================= */

    if(topic === "aquarium/pumpoutstatus"){

        latestData.pumpout =
        data;

    }

    /* =========================
    PUMP IN
    ========================= */

    if(topic === "aquarium/pumpinstatus"){

        latestData.pumpin =
        data;

    }

    updateUI();

});

/* =========================
UPDATE UI
========================= */

function updateUI(){

    let ph =
    Number(latestData.ph) || 0;

    let temp =
    Number(latestData.temp) || 0;

    let turbidity =
    latestData.turbidity;

    /* =========================
    SENSOR VALUE
    ========================= */

    phValue.innerHTML =
    ph.toFixed(1);

    tempValue.innerHTML =
    temp + "°C";

    turbidityValue.innerHTML =
    turbidity;

    /* =========================
    REALTIME DEVICE STATUS
    ========================= */

    ledPh.innerHTML =
    latestData.ledph;

    ledTemp.innerHTML =
    latestData.ledtemp;

    pumpOut.innerHTML =
    latestData.pumpout;

    pumpIn.innerHTML =
    latestData.pumpin;

/* =========================
LED STATUS LOGIC
========================= */

if(latestData.ledph === "ON"){

    ledPhStatus.innerHTML =
    "Unsafe pH";

    ledPhStatus.className =
    "status bad";

}
else{

    ledPhStatus.innerHTML =
    "pH Safe";

    ledPhStatus.className =
    "status good";

}

if(latestData.ledtemp === "ON"){

    ledTempStatus.innerHTML =
    "Unsafe Temperature";

    ledTempStatus.className =
    "status bad";

}
else{

    ledTempStatus.innerHTML =
    "Temperature Safe";

    ledTempStatus.className =
    "status good";

}

    /* =========================
    PH LOGIC
    ========================= */

    if(ph < 6 || ph > 8){

        phStatus.innerHTML =
        "Unsafe";

        phStatus.className =
        "status bad";

    }

    else{

        phStatus.innerHTML =
        "Normal";

        phStatus.className =
        "status good";

    }

    /* =========================
    TEMP LOGIC
    ========================= */

    if(temp < 25 || temp > 30){

        tempStatus.innerHTML =
        "Unstable";

        tempStatus.className =
        "status bad";

    }

    else{

        tempStatus.innerHTML =
        "Stbale";

        tempStatus.className =
        "status good";

    }

    /* =========================
    TURBIDITY LOGIC
    ========================= */

    if(turbidity === "CLEAR WATER"){

        turbidityStatus.innerHTML =
        "CLEAR";

        turbidityStatus.className =
        "status good";

    }

    else if(turbidity === "CLOUDLY WATER"){

        turbidityStatus.innerHTML =
        "Cloudly";

        turbidityStatus.className =
        "status bad";

    }

    else if(turbidity === "VERY CLOUDLY WATER"){

        turbidityStatus.innerHTML =
        "Very Cloudly";

        turbidityStatus.className =
        "status bad";

    }

    else{

        turbidityStatus.innerHTML =
        "Sensor Dry";

        turbidityStatus.className =
        "status bad";

    }

}

/* =========================
MANUAL CONTROL
========================= */

function pumpOutOn(){

    client.publish(
        "aquarium/pump1",
        "ON"
    );

    alert("Drain Pump ON");

}

function pumpOutOff(){

    client.publish(
        "aquarium/pump1",
        "OFF"
    );

    alert("Drain Pump OFF");

}

function pumpInOn(){

    client.publish(
        "aquarium/pump2",
        "ON"
    );

    alert("Refill Pump ON");

}

function pumpInOff(){

    client.publish(
        "aquarium/pump2",
        "OFF"
    );

    alert("Refill Pump OFF");

}

/* =========================
HISTORY
========================= */

function addHistory(){

    let ph =
    latestData.ph;

    let temp =
    latestData.temp;

    let turbidity =
    latestData.turbidity;

    let status =
    "Normal";

    let statusClass =
    "good";

    if(

        ph < 6 ||
        ph > 8 ||
        temp < 25 ||
        temp > 30 ||
        turbidity !== "CLEAR WATER"

    ){

        status =
        "Warning";

        statusClass =
        "bad";

    }

    let now =
    new Date();

    let time =
    now.toLocaleTimeString();

    let row =
    `
    <tr>

        <td>${time}</td>

        <td>${ph.toFixed(1)}</td>

        <td>${turbidity}</td>

        <td>${temp}°C</td>

        <td>

            <span class="table-status ${statusClass}">
                ${status}
            </span>

        </td>

    </tr>
    `;

    historyBody.innerHTML =
    row + historyBody.innerHTML;

    if(historyBody.rows.length > 10){

        historyBody.deleteRow(10);

    }

}

setInterval(addHistory, 5000);

/* =========================
SCROLL REVEAL
========================= */

window.addEventListener("scroll", reveal);

function reveal(){

    let reveals =
    document.querySelectorAll(".reveal");

    for(let i = 0; i < reveals.length; i++){

        let windowHeight =
        window.innerHeight;

        let elementTop =
        reveals[i].getBoundingClientRect().top;

        let elementVisible =
        100;

        if(elementTop < windowHeight - elementVisible){

            reveals[i].classList.add("active");

        }

    }

}

updateUI();

reveal();

// =========================
// SHOW USERNAME
// =========================

const usernameDisplay =
document.getElementById(
    "username-display"
);

if(usernameDisplay){

    usernameDisplay.innerHTML =
    localStorage.getItem("username");

}