const endpoint = "http://192.168.178.60";
let datas = {};
$(document).ready(function(){
    console.log("once");
    setInterval(() => {
        myTimer();
        getData();
    }, 1000);

            
    $("#ambiance-light-btn").click(function() {
            if (datas.state.ambiance_light == true) {
                $.get(`${endpoint}/api/device?id=ambiance_light&action=off&data=-`, (data) => {
                    $("#ambiance-light-btn").addClass("light-button-off");
                    $("#ambiance-light-btn").removeClass("light-button-on");
                });
                return;
            }
            if (datas.state.ambiance_light == false) {
                $.get(`${endpoint}/api/device?id=ambiance_light&action=on&data=-`, (data) => {
                    $("#ambiance-light-btn").addClass("light-button-on");
                    $("#ambiance-light-btn").removeClass("light-button-off");
                });
                return;
            }
        
    
        // $.get(`${endpoint}/api/device?id=ambiance_light&action=on&data=-`, (data) => {
            
        // });
    });
});


function myTimer() {
    var d = new Date();
    $('.digital-clock').text("Local Time: " + d.toLocaleTimeString());
}


function getData() {
    $.get(`${endpoint}/api/currentstate`, ( data ) => {
        // set all data from api
        if(data.state){
            // set climate info
            $('.temp').text("Temperature: " + data.state.main_temp + "°C");
            $('.hum').text("Humidity: " + data.state.main_hum + "%");

            // set text for motion
            if(data.state.motion){
                $('.motion').text("Motion detected!");
            }else if(!data.state.motion){
                $('.motion').text("No motion detected");
            }

            // insert once
            if(jQuery.isEmptyObject(datas)){

                // set lights state
                if(data.state.ambiance_light){
                    $("#ambiance-light-btn").addClass("light-button-on");
                }else if(!data.state.ambiance_light){
                    $("#ambiance-light-btn").addClass("light-button-off");
                }
            }
        }

        datas = data;
        console.log(datas);
        console.log( "Load was performed." );
    });

}

function turnLights(){
    if (currentState.main_light) {
        if (currentState.main_light == true) {
            $.get(`${endpoint}/api/device?id=ambiance_light&action=off&data=-`, (data) => {
        
            });
            return;
        }
    }

    $.get(`${endpoint}/api/device?id=ambiance_light&action=on&data=-`, (data) => {
        
    });
}