const apiUrl = "http://localhost:8080/api"
let socket = new WebSocket("ws://localhost:8080/ws");

let idSet = new Set();

socket.onmessage = function(event) {

    console.log(event.data);
    let json_data = JSON.parse(event.data);
    let method = json_data.method;
    console.log(method);
    switch(method){
        case "updateHtml":
            put_htmls(json_data.data);
            break;
        case "changeText":
            change_text(json_data)
            break;
    }


}

function change_text(json){
    let id = json.id;
    let datas = json.datas;
    let new_text = datas.newText;
    document.getElementById(id).textContent = new_text;
}

function put_htmls(elements){
    let container = document.getElementById("container");
    let addElems = elements.add;
    let delElems = elements.delete;
    for(const id of delElems) {
        idSet.delete(id);
        let elem = document.getElementById(id);
        if(elem) {
            elem.parentNode.removeChild(elem);
        }
    }
    for(const elem of addElems){
        
        let id = elem.id;
        let type = elem.type;
        let styles = elem.styles;
        let text = elem.text;
        let style = "";
        if(idSet.has(id)){
            continue;
        }
        idSet.add(id);
        for(const prop in styles){
            let value = styles[prop];
            style += `${prop}: ${value};`
        }
        let style_attribute = Object.keys(styles).length > 0 ? `style="${style}"` : "";
        console.log(styles, style)
        switch(type){
            case "button":
                container.insertAdjacentHTML("beforeend", `<button id="${id}" ${style_attribute}">${text}</button>`)
                let button = document.getElementById(id);
                button.addEventListener("mousedown", buttonPressed);
                button.addEventListener("mouseup", buttonReleased);
                break;
            case "label":
                container.insertAdjacentHTML("beforeend", `<p id="${id}" ${style_attribute}">${text}</p>`);
                break;
            case "textInput":
                container.insertAdjacentHTML("beforeend", `<input type="text" id="${id}" ${style_attribute} />`);
                let text_input = document.getElementById(id);
                text_input.addEventListener("input", textChanged);
                break;
        }
    }
}

function buttonPressed(event){
    const data = {id: event.target.id};
    const formBody = new URLSearchParams(data);
    fetch(`${apiUrl}/elements/buttonPressed`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formBody.toString()
    });
}

function buttonReleased(event) {
    const data = {id: event.target.id};
    const formBody = new URLSearchParams(data);
    fetch(`${apiUrl}/elements/buttonReleased`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formBody.toString()
    });
}

function textChanged(event) {
    const data = {id: event.target.id, new_text: event.target.value};
    const formBody = new URLSearchParams(data);
    fetch(`${apiUrl}/elements/textChanged`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formBody.toString()
    });
}

socket.onopen = function(event) {
    console.log("open socket");
}

socket.onclose = function(event) { 
    console.log("close socket");
}

socket.onerror = function(event) {
    console.log("error");
}