Source: session.js

/*
Copyright (C) 2021 Velometrik GmbH
<http://www.velometrik.de/>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


/* 
    Created on : 04.06.2021, 21:08:29
    Author     : Peter Bauer
*/
const host = `http://${location.host}`;
const ws = `ws://${location.host}`;
const apps= "satteldruckanalyse";
function ToggleLog() {
    if(getFromLocalStorage('log')===false||false){
        saveToLocalStorage('log',true)
        log=true
    } else{
        saveToLocalStorage('log',false)
    }
}

const session = new WebSocket(`${ws}/apps/${apps}`, ["soap", "wamp"]);

var fi = 0
var recID =[];

saveToLocalStorage('session',"")
saveToLocalStorage('session_note',"")
clearFromLocalStorage(['sessionID'])
/* A variable that is used to store a function that is called when the server sends a message to the
client. */
var onsqlresult = getLog;

function getLog(params){
    console.log(params);
}

let inter = setInterval(()=> {
    console.log('box_status', box_status);
    if(location.pathname === '/production/client.tcls' && box_status.includes('LOGGED_IN')){
        AXIOS_Ping()
    }
      clearInterval(inter);
}, 1500);





var galerie_image_info = {};

session.onopen = (e) => {
    if(location.pathname === "/production/clients.tcls"){
        document.getElementById('loader').classList.add('hidden')
        end_session()
        onsqlresult = clients_list;
        session.send(`sql select * from clients order by client_id desc`)
    }
};

var galerie_image_info = {};

/* A function that is called when the server sends a message to the client. */
session.onmessage = (e) => {

    var data = new Object();
    try {
       data = JSON.parse(e.data);
    } catch (error) {
        getError(error)
    }

    if (data.wsevent === "sqlresult"){
        onsqlresult (data.rows);
    }
    if(data.wsevent === "result3"){
        galerie_image_info = data;
    }
    if (data.wsevent === "sda_int3") {
        var pel;
        // console.log(galerie_image_info);
        sda_frame3 = `${host}/sattelbild?image=sda_int3&rnd=${(new Date).getTime()}`;
        document.getElementsByClassName('imgGal1')[fi-1].src=sda_frame3
        // if(galerie_image_info.pelvisrotation)
        // pel = `${galerie_image_info.pelvisrotation.width||""}:${galerie_image_info.pelvisrotation.height||""}`
        // else
        // pel ="-"
        // document.getElementsByClassName('info_img')[fi-1].innerHTML =`
        // <ul class="uk-list uk-list-collapse">
        // <li>Veloscore</li>
        // <li>Rotation</li>
        // <li>Lins/Rechts</li>
        // <li>Vorn/Hinten</li>
        // </ul>
        // <ul class="uk-list uk-list-collapse">
        // <li>${galerie_image_info.veloscore}</li>
        // <li>${pel}</li>
        // <li>${galerie_image_info.left_right}</li>
        // <li>${galerie_image_info.front_rear}</li>
        // </ul>`

        if(recID[fi]){
            // console.log('wsevent int3 send');
            session.send(`recording retrieve ${recID[fi]}`)
            fi++
        }
    }

}

/**
 * It sends a message to the server to start a new session
 * @param {boolean} bool - if true, the user will be redirected to the next page, if false, the session will be
 * finished.
 */
function new_session(bool) {
    const form = document.forms.namedItem("session_form");
    if(form.forename.value != "" && form.surname.value != "" && bool === true){
        saveToLocalStorage('session',`start {"forename":"${form.forename.value.trim()}","surname":"${form.surname.value.trim()}","email":"${form.email.value.trim()||""}"}`)
        saveToLocalStorage('client_name',`${form.forename.value.trim()} ${form.surname.value.trim()}`)
        saveToLocalStorage('client_mail',`${form.email.value.trim()||""}`)
        saveToLocalStorage('client_forenames',`${form.forename.value.trim()}`)
        saveToLocalStorage('client_surename',`${form.surname.value.trim()}`)
        location.href = '/production/anamnese.tcls'
        //location.href = '/production/saddle_pressure_analysis.tcls'
    } else{
        if(form.forename.value === "")
        form.forename.setAttribute('style','border: 1px solid red')
        if(form.surname.value === "")
        form.surname.setAttribute('style','border: 1px solid red')
    }
    if(form.forename.value != "" && form.surname.value != "" && bool === false){
        session.send(`session start {"forename":"${form.forename.value.trim()}","surname":"${form.surname.value.trim()}","email":"${form.email.value.trim()||""}"}`)
        session.send(`session finish`)
        location.pathname = '/production/clients.tcls'
    } else{
        if(form.forename.value === "")
        form.forename.setAttribute('style','border: 1px solid red')
        if(form.surname.value === "")
        form.surname.setAttribute('style','border: 1px solid red')
    }

}

/**
 * It sends a message to the session.
 */
function end_session(){
    session.send('session finish')
}

/**
 * It takes an array of objects and creates a table with the objects as rows.
 * @param {String[]} array - the array of objects that you want to display
 */
function clients_list(array) {
    onsqlresult=getLog;
    var thead = ['#','Datum der Messung','Name/Vorname','Email']//,'new Session','']
    var append = $('#clients-list')[0]
    var container = document.createElement('div')
    container.classList.add('uk-container','uk-padding-remove')
    append.append(container)
    var table = document.createElement('table')
    table.classList.add('uk-table','uk-table-middle','uk-table-divider','uk-table-hover')
    container.append(table);
    var table_head= document.createElement('thead')
    table.append(table_head);
    var tr_head = document.createElement('tr');
    table_head.append(tr_head);
    thead.forEach(element => {
        var head = document.createElement('th');
        head.setAttribute('key',element)
        head.innerHTML = element
        tr_head.append(head);
    })
    var tbody = document.createElement('tbody');
    table.append(tbody);

    array.forEach(element => {
        var x = new Object;
        x = element;
        var tr_body = document.createElement('tr');
        tr_body.classList.add('suche')
        tr_body.setAttribute('suche',`${x.surname||""} ${x.forename||""} ${x.first_contact} ${x.email||""}`)
        tbody.append(tr_body);
        tr_body.innerHTML =  `<td onclick="info(${x.client_id},'${x.surname||""} ${x.forename||""}','${x.forename||""}','${x.surname||""}','${x.email||""}','${x.first_contact}')">${x.client_id}</td>`
        tr_body.innerHTML += `<td onclick="info(${x.client_id},'${x.surname||""} ${x.forename||""}','${x.forename||""}','${x.surname||""}','${x.email||""}','${x.first_contact}')">${x.first_contact}</td>`
        tr_body.innerHTML += `<td onclick="info(${x.client_id},'${x.surname||""} ${x.forename||""}','${x.forename||""}','${x.surname||""}','${x.email||""}','${x.first_contact}')">${x.forename||""} ${x.surname||""}</td>`
        tr_body.innerHTML += `<td onclick="info(${x.client_id},'${x.surname||""} ${x.forename||""}','${x.forename||""}','${x.surname||""}','${x.email||""}','${x.first_contact}')">${x.email||""}</td>`
        // tr_body.innerHTML += `<td><button class="uk-button uk-button-default uk-button-small" uk-icon="icon: play" onclick="new_session_id(${x.client_id})" uk-tooltip="Neue Sitzung"></button></td>`
         tr_body.innerHTML += `<td><button class="uk-button uk-button-default uk-button-small adba basicview ico-16 mdi mdi-trash-can-outline" onclick="ClientDel(${x.client_id})"></button></td>`
    });
    ToggleViewMode(getFromLocalStorage("viewmode"));
    translatejs()
}

/**
 * `ClientInfo` is a function that takes a single parameter, `params`, and stores it in local storage
 * @param params - {
 */
function ClientInfo(params) {
    onsqlresult = getLog;
    saveToLocalStorage('client_info',JSON.stringify(params));
}

/**
 * It takes three arguments, sends a query to the database, and then creates a table with the results
 * of the query
 * @param {number}client_id - The client's ID
 * @param {string}name - The name of the client
 * @param {string}mail - The email address of the user.
 */
function info(client_id,name,fname,lname,mail,fc) {
    onsqlresult = ClientInfo
    session.send(`sql select * from sessions where client_id=${client_id}`);
    //append1 = document.getElementById('imagelist');
    //append1.innerHTML = "";
    let inter = setInterval(()=> {
        saveToLocalStorage('client_fc',fc)
        saveToLocalStorage('client_name',name)
        saveToLocalStorage('client_mail',mail)
        saveToLocalStorage('client_id',client_id)
        saveToLocalStorage('client_forenames',fname)
        saveToLocalStorage('client_surename',lname)
        location.href = "/production/client.tcls"
        clearInterval(inter);
      }, 500);

}

/**
 * It sets the title of the modal to the session number and shows the modal
 * @param params - The name of the session to be deleted
 */
function SessionDel(params) {
    let text = `${aLangKeys[lang]['cli_session_del1']}${params} ${aLangKeys[lang]['cli_session_del2']}`
    OpenModDialog({type:'warn',title:text,msg:["cli_session_text"],master_btn:['button_delete','SelectSessionDel()'],slave_btn:['button_cancel']})
    saveToLocalStorage('del_session', params)
}

function ClientDel(params) {
    let text = `${aLangKeys[lang]['cli_client_del1']}${params} ${aLangKeys[lang]['cli_session_del2']}`
    OpenModDialog({type:'warn',title:text,msg:["cli_client_text"],master_btn:['button_delete','SelectCliDel()'],slave_btn:['button_cancel']})
    saveToLocalStorage('del_cli', params)
}

function SelectCliDel() {
    session.send(`sql delete from sessions where client_id=${getFromLocalStorage('del_cli')}`)
    session.send(`sql delete from clients where client_id=${getFromLocalStorage('del_cli')}`)
    location.reload()
}

/**
 * It deletes the session and all recordings associated with it
 */
function SelectSessionDel() {
    session.send(`sql delete from recordings where session_id=${getFromLocalStorage('del_session')}`)
    session.send(`sql delete from sessions where session_id=${getFromLocalStorage('del_session')}`)
    let del = document.getElementById(`cli_${getFromLocalStorage('del_session')}`)
    del.classList.add('hidden')
}

/**
 * It takes an array of objects as a parameter, and for each object in the array, it creates an image
 * element, sets the width and height, and adds a class to the image element
 * @param params - The array of objects returned from the SQL query.
 */
function RowImg(params) {
    // session.send()
    if(params.length == 0){
        document.getElementById('pi_retriveSession').innerHTML = `<button key="cli_NoSession" class="uk-button uk-button-primary uk-modal-close"><!--fortsetzen--></button>`;
    }
    fi = 0;
    recID = [];
    onsqlresult = getLog;
    var append1 = document.getElementById('imagelist')
    append1.innerHTML ="";
    params.forEach(element => {
            if(fi===0){
                console.log(`%c websocet: recording retrieve ${element.recording_id}`,'background: #222;color: white;padding:1em');
                session.send(`recording retrieve ${element.recording_id}`)
                fi++
            }
            recID.push(element.recording_id)
            let div = document.createElement('div');
            div.setAttribute('style','border:1px solid green;margin: 5px;')
            append1.append(div);
            let img = document.createElement('img');
            img.width=100
            img.height=100
            img.classList.add('imgGal1')
            div.append(img)
            let div_info = document.createElement('div');
            div_info.classList.add('uk-grid','uk-child-width-1-2','info_img')
            div_info.setAttribute('style','margin: 0 -30px;')
            // div_info.innerHTML =`<ul><li>data</li></ul><ul><li>${galerie_image_info.product_label}</li></ul>`
            div.append(div_info)
    });
}

/**
 * `session_img(session_id)` is a function that sends a SQL query to the database to get the image
 * associated with the session_id.
 * @param session_id - The session ID of the recording you want to retrieve.
 */
function session_img(session_id,note) {
    saveToLocalStorage('sessionID',session_id)
    onsqlresult = RowImg
    if(location.pathname === '/production/client.tcls'){
        document.getElementById('details_info').innerHTML = note || session_id;
        document.getElementById('pi_retriveSession').innerHTML = `<button key="cli_to_pdf" onclick='toProtokoll(${session_id})' class='uk-button uk-button-default'><!--protokoll--></button>
                                                                  <button key="cli_to_gal" onclick='LinkTo("galerie.tcls")' class='uk-button uk-button-default'><!--bread_galerie--></button>
                                                                  <button key="cli_retrive" onclick='rest_session(${session_id},"${note}")' class="uk-button uk-button-primary"><!--fortsetzen--></button>`;
        UIkit.modal('#modal_details').show(); 
    }
    translatejs();
    saveToLocalStorage('session_note',note)
    // session.send(`sql select * from recordings where session_id=${session_id}`)
    session.send(`sql SELECT * FROM recordings WHERE analysis=2 AND session_id=${session_id} ORDER BY finished`)
}

/**
 * `rest_session(id)`
 * 
 * This function is called when the user clicks the "Restart" button. It sends a message to the server
 * that the session is finished, and then redirects the user to the start page
 * @param id - the id of the session
 */
function rest_session(id,note){
    session.send('session finish');
    saveToLocalStorage('session',`restart ${id}`)
    saveToLocalStorage('session_note',note)
    if(localStorage.getItem('dev')){
         location.href = '/production/saddle_pressure_analysis_test.tcls'
    } else {
        location.href = '/production/saddle_pressure_analysis.tcls'
    }
}

/**
 * It sends a message to the server that the session is finished, then it sets the session id in the
 * local storage, and then it redirects the user to the next page
 * @param id - the id of the session
 */
function new_session_id(id){
    session.send('session finish');
    saveToLocalStorage('session',`start ${id}`)
    saveToLocalStorage('session_note',"")
    // DEF SITZKNOCHEN
    location.href = '/production/anamnese.tcls'
    //location.href = '/production/saddle_pressure_analysis.tcls'
}


/**
 * It searches for the given parameter in the attribute 'suche' of all elements with the class 'suche'
 * and shows the elements that contain the parameter.
 * @param params - The search term
 */
function suche(params) {
    $('.suche').each(element => {
        $('.suche')[element].classList.add('hide')
        if($('.suche')[element].getAttribute('suche').includes(params)|| $('.suche')[element].getAttribute('suche').toLowerCase().includes(params))
        $('.suche')[element].classList.remove('hide')
    });
}
var Stationsinfo;
/**
 * The AXIOS_Ping function sends a GET request to a specific endpoint and handles the response data
 * accordingly, including error handling.
 */
function AXIOS_Ping() {
    axios.get(`/vlbservice/ping`, {
            method: 'GET',
            withCredentials: true
        })
        .then(response => {
          console.log('response',response);
            if (response.data === '12 forbidden') {
                //TODO ERROR HANDLING
                OpenModDialog({type:'error',title:["error"],msg:`${response.data}`,master_btn:['button_ok']})
                
                console.log('error');
                return;
            }
            console.log('ping', response.data);
            Stationsinfo = response.data;
            let Options = Stationsinfo.optionen
            let mail = getFromLocalStorage('client_mail')
            for (const key in Options) {
                    const element = Options[key];
                    console.log(key,element);
                    if(['sattel.beratung', 'fahrraeder.beratung', 'ergodreieck.beratung'].includes(key)&&mail!=''){
                        var date1 = new Date(element)
                        var date2 = new Date()
                        var div = document.getElementById('client_addon')
                        div.style = 'justify-content: space-between;' 
                        if(date1 > date2){
                            var type = key.split('.')[0]
                            //<div class="cur_pointer card_hover" style="border:1px solid var(--light-1); width: 10em;height: 10em;background-image: url('/production/images/tpfs.png');background-repeat: no-repeat;background-size: contain;" onclick="openTPFS('ergodreieck')"></div>
                            newElement({element:'div',id:`tpfs_addon_${type}`,cls:['cur_pointer','card_hover'],attr:[['style',`border:1px solid var(--light-1); width: 10em;height: 10em;background-image: url('/production/images/svg/${type}.png');background-repeat: no-repeat;background-size: contain;`],['onclick',`openTPFS('${type}')`]]},div)
                        }
                        
                    }
                    
            }
            //time_to_use(Stationsinfo.optionen['sattel.beratung'])
            translatejs();
        })
        .catch(err => {
            //TODO ERROR HANDLING
            OpenModDialog({type:'error',title:["error"],msg:`${err}`,master_btn:['button_ok']})
        });
}

document.addEventListener('keydown', (event) => {
    if (event.key === 'Enter' && location.pathname === "/production/newclient.tcls") {
        new_session(false)
    }
});

function openTPFS(param){
    saveToLocalStorage('tpfs',param)
    LinkTo('tpfs.tcls')
}