Source: anamnese.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.05.2021, 21:08:29
    Author     : Peter Bauer
*/

const host = `http://${getFromLocalStorage('smartcube')}`;
const ws = `ws://${getFromLocalStorage('smartcube')}`;
const setting = {
  text_color: '#ffffff',
};

const cw = document.getElementsByClassName("ska")[0].offsetWidth;
saveToLocalStorage('sk', '');

const host_2 = location.origin;
const ws_2 = host_2.replace('http', 'ws');
const apps = "satteldruckanalyse";
const apps_ska = "sitzknochenabstand"

const sessionID = getFromLocalStorage('session').split(" ")[0] === 'restart' ? 
  getFromLocalStorage('session').split(" ")[1] : 
  getFromLocalStorage('new_session');

const canvas_ska = new fabric.Canvas("ska_img");
createCanvas(canvas_ska);
//setImage(canvas_ska, `/production/images/Sitzknochenvermessung.png`);
setImage(canvas_ska,`/production/images/ska.png`);

let cm, inch, vsum = 0;

translatejs();
_name();

let ws_ska;
try {
  ws_ska = new WebSocket(`${ws}/apps/${apps_ska}`, ["soap", "wamp"]);
} catch (error) {
  OpenMod('disconected');
}

let ws_ska_2;
try {
  ws_ska_2 = new WebSocket(`${ws_2}/apps/${apps_ska}`, ["soap", "wamp"]);
} catch (error) {
  OpenMod('disconected');
}

let sattelanalyse;
try {
  sattelanalyse = new WebSocket(`${ws_2}/apps/${apps}`, ["soap", "wamp"]);
} catch (error) {
  console.error(error);
}

const analysis = sessionStorage.getItem('analysis') ? JSON.parse(sessionStorage.getItem('analysis')) : {
  sitbones: {},
  anamnesis: {},
  x1: {},
};

let a = setInterval(()=> {
  for (const key in analysis) {
    const element = analysis[key];
    console.log(element,key);
    for (const k in element) {
        const e = element[k];
        console.log(e,k);
        document.getElementById(k).value = e
    }
    if(element.sitzknochenabstand){
    
    }
}
  clearInterval(a);
},1000)



//sattelanalyse.onopen = () => {
//  //sattelanalyse.send(`session start ${sessionID}`);
//  //sattelanalyse.send(`analysis ["sitbones","anamnesis","x1"]`);
//};

sattelanalyse.onmessage = (e) => {
  const data = JSON.parse(e.data);
  //console.log(data); //TODO DEF
  if (data.wsevent === "analyses") {
    const d = data.analyses;
    for (const key in d) {
      const element = d[key];
      for (const key2 in element) {
        const element2 = element[key2];
        const ele = document.getElementById(key2);
        ele.value = element2;
        analysis[key][key2] = element2;
      }
    }
  }
};

ws_ska.onmessage = (e) => {
  translatejs();
  const data = JSON.parse(e.data);
  console.log(data);

  //if (data.v_sum === 0.0) {
  //  vsum = 0;
  //}

  if (data.wsevent === 'plugged') {
    OpenMod('connected');
    document.getElementById('glow').classList.add('glow');
  }

  if (data.wsevent === 'hockerbild') {
    console.log("draw image");
    let img = `${host}/hockerbild?rnd=${(new Date).getTime()}`;
    console.log(img);
    setImage(canvas_ska, img);
  }

  if (data.wsevent === 'sitzknochenabstand' && vsum === 0) {
    vsum = 1;
    store(data.sitzknochenabstand, "sitzknochenabstand", "sitbones");
    document.getElementById('sitzknochenabstand').value = data.sitzknochenabstand;

    const inter = setInterval(() => {
      draw_cross(canvas_ska, [(data.schwerpunkt1_x + 0.5) * (cw / 28), (cw / 1.75) - (data.schwerpunkt1_y + 0.5) * (cw / 28)]);
      draw_cross(canvas_ska, [(data.schwerpunkt2_x + 0.5) * (cw / 28), (cw / 1.75) - (data.schwerpunkt2_y + 0.5) * (cw / 28)]);
      console.log(lineDistance(
        [data.schwerpunkt1_x * (cw / 28), (cw / 1.75) - data.schwerpunkt1_y * (cw / 28)], 
        [data.schwerpunkt2_x * (cw / 28), (cw / 1.75) - data.schwerpunkt2_y * (cw / 28)]
      ) / (cw / 28));
      cm_inch(data.sitzknochenabstand);
      document.getElementById('val').value = `${cm}`; //<br> ${inch}`
      saveToLocalStorage('sk', `${cm}`);
      vsum++;
      clearInterval(inter);
    }, 1000);
  }
};

ws_ska_2.onmessage = (e) => {
  translatejs();
  const data = JSON.parse(e.data);
  console.log(data);

  //if (data.v_sum === 0.0) {
  //  vsum = 0;
  //}

  if (data.wsevent === 'plugged') {
    OpenMod('connected');
    document.getElementById('glow').classList.add('glow');
  }

  if (data.wsevent === 'hockerbild') {
    console.log("draw image");
    let img = `${host_2}/hockerbild?rnd=${(new Date).getTime()}`;
    console.log(img);
    setImage(canvas_ska, img);
  }

  if (data.wsevent === 'sitzknochenabstand' && vsum === 0) {
    vsum = 1;
    store(data.sitzknochenabstand, "sitzknochenabstand", "sitbones");
    document.getElementById('sitzknochenabstand').value = data.sitzknochenabstand;

    const inter = setInterval(() => {
      draw_cross(canvas_ska, [(data.schwerpunkt1_x + 0.5) * (cw / 28), (cw / 1.75) - (data.schwerpunkt1_y + 0.5) * (cw / 28)]);
      draw_cross(canvas_ska, [(data.schwerpunkt2_x + 0.5) * (cw / 28), (cw / 1.75) - (data.schwerpunkt2_y + 0.5) * (cw / 28)]);
      console.log(lineDistance(
        [data.schwerpunkt1_x * (cw / 28), (cw / 1.75) - data.schwerpunkt1_y * (cw / 28)], 
        [data.schwerpunkt2_x * (cw / 28), (cw / 1.75) - data.schwerpunkt2_y * (cw / 28)]
      ) / (cw / 28));
      cm_inch(data.sitzknochenabstand);
      document.getElementById('val').value = `${cm}`; //<br> ${inch}`
      saveToLocalStorage('sk', `${cm}`);
      vsum++;
      clearInterval(inter);
    }, 1000);
  }
};

function lineDistance(p1, p2) {
  return Math.hypot(p2[0] - p1[0], p2[1] - p1[1]);
}

function draw_cross(ele, pos) {
  console.log(pos);
  const c = ele.getContext('2d');
  c.lineWidth = 5;
  c.strokeStyle = setting.text_color;

  c.beginPath();
  c.moveTo(pos[0], pos[1]);
  c.lineTo(pos[0], pos[1] + 10);
  c.stroke();

  c.beginPath();
  c.moveTo(pos[0], pos[1]);
  c.lineTo(pos[0], pos[1] - 10);
  c.stroke();

  c.beginPath();
  c.moveTo(pos[0], pos[1]);
  c.lineTo(pos[0] + 10, pos[1]);
  c.stroke();

  c.beginPath();
  c.moveTo(pos[0], pos[1]);
  c.lineTo(pos[0] - 10, pos[1]);
  c.stroke();
}

/**
 * The function converts a measurement in centimeters to inches.
 * @param params - The parameter "params" in the given function represents the length in centimeters
 * that needs to be converted to inches.
 */
function cm_inch(params) {
  cm = `${params.toFixed(2)} cm`;
  inch = params / 2.54;
  inch = `${inch.toFixed(2)} inch`;
}

/**
 * It takes a canvas, an image, and a boolean, and then it adds the image to the canvas, and then it
 * draws the text and the grid if the boolean is true
 * @param params - the canvas object
 * @param img - the image to be loaded
 * @param grid - boolean, whether to draw the grid or not
 */
function setImage(params, img) {
  fabric.Image.fromURL(img, (oImg) => {
    oImg.scaleToWidth(cw);
    oImg.hasControls = false;
    oImg.set("selectable", false);
    params.add(oImg);
  });
}

/**
 * Create a canvas object with the given parameters, and set the height and width to the values of the
 * global variables cw and ch.
 * @param params - The object that contains the parameters for the canvas.
 */
function createCanvas(params) {
  params.selection = false; // disable group selection
  params.hasControls = false;
  params.lockMovement = false;
  params.setHeight(cw / 1.75);
  params.setWidth(cw);
}

/**
 * The function opens a UIkit modal with the ID specified in the parameter.
 * @param params - The parameter `params` is a string that represents the ID of the modal that needs to
 * be opened. The function `OpenMod` takes this parameter and uses it to show the corresponding modal
 * using the UIkit framework.
 */
function OpenMod(params) {
  UIkit.modal(`#modal-${params}`).show();
}

/**
 * It gets the name from local storage and puts it in the right places
 */
function _name() {
  const name = getFromLocalStorage('client_name').split(' ');
  document.getElementById('name_vorname').innerHTML = `${name[0]}, ${name[1]}`;
}

function store(val, key, a) {
  analysis[a][key] = val;
  sessionStorage.setItem('analysis',JSON.stringify(analysis))
  //for (const key in analysis) {
  //  const element = analysis[key];
  //  sattelanalyse.send(`analysis {"${key}":${JSON.stringify(element)}}`);
  //  if (log) {
  //    console.log('store', `analysis {"${key}":${JSON.stringify(element)}}`);
  //  }
  //}
}

//CUSTOM PROTOCOL
const custom_placeholder = document.getElementById('custom_placeholder')

let interC = setInterval(()=> {
    if(script_setting.custom_protocol && script_setting.customprotocol){
        if(new Date(script_setting.custom_protocol) > new Date()){
            let head = document.getElementById('custom_head')
            head.classList.remove('hidden')
            time_to_use_custom_pro(script_setting.custom_protocol)
            for (const category in customJSN) {
                if (Object.hasOwnProperty.call(customJSN, category)) {
                    const fields = customJSN[category];
                    const categoryS = category.replaceAll(' ','_').replaceAll('(','').replaceAll(')','').replaceAll('&','u').replaceAll('%','')
                    //console.log(category,fields);
                    let card    = newElement({element:"div",cls:['uk-card']},custom_placeholder);
                    let head    = newElement({element:"div",cls:['uk-card-header']},card);
                    let grid    = newElement({element:"div",cls:['uk-grid-small','uk-flex-middle'],attr:[['uk-grid',' ']]},head);
                    let headG   = newElement({element:"div",cls:['uk-width-expand','flexCenter-R'],attr:[['style','border-bottom: 1px solid var(--light-1);']]},grid);
                    let h3      = newElement({element:"h3",cls:['uk-card-title']},headG).innerHTML = category;
                    //let inpchk  = newElement({element:"input",cls:['form-control','uk-checkbox','checkbox-A'],id:`check_${categoryS}`,attr:[['checked','true'],['type','checkbox'],['name',`${categoryS}`]]},headG)
                    //let hr      = newElement({element:"hr"},card);
                    let body    = newElement({element:"div",cls:['uk-card-body']},card)

                    let grid2   = newElement({element:"div",attr:[['uk-grid',' ']]},body);
                    let left    = newElement({element:"div",cls:['uk-width-1-2'],id:'custom_left'},grid2);
                    let right   = newElement({element:"div",cls:['uk-width-1-2'],id:'custom_right'},grid2);

                    let x = 0
                    fields.forEach(field => {
                        if(x==0){
                            let p       = newElement({element:"p",cls:['uk-margin-remove']},left).innerHTML = field;
                            let inline  = newElement({element:"div",cls:['uk-inline']},left)
                            let inp     = newElement({element:"input",id:`pro_${categoryS}_${field.replaceAll(' ','_')}`,cls:['uk-input','uk-form-width-small'],attr:[['type','text'],['onchange',`store(this.value,"pro_${categoryS}_${field.replaceAll(' ','_')}","x1")`]]},left);
                            x++
                        } else {
                            let p       = newElement({element:"p",cls:['uk-margin-remove']},right).innerHTML = field;
                            let inline  = newElement({element:"div",cls:['uk-inline']},right)
                            let inp     = newElement({element:"input",id:`pro_${categoryS}_${field.replaceAll(' ','_')}`,cls:['uk-input','uk-form-width-small'],attr:[['type','text'],['onchange',`store(this.value,"pro_${categoryS}_${field.replaceAll(' ','_')}","x1")`]]},right);
                            x=0
                        }

                    });

                }
            }

        }
    }
    clearInterval(interC);
  }, 1000);

/**
 * The function calculates the number of days between a given date and the current date, and displays a
 * warning message if the difference is less than 60 days.
 * @param params - It looks like the `params` variable is expected to be a date value that is passed
 * into the `time_to_use_custom_pro` function. The function then calculates the number of days between
 * the provided date and the current date.
 */
  function time_to_use_custom_pro(params) {
    console.log(params);
    let date = new Date(params)
    let today = new Date();
    let days = `${Math.floor((date - today) / (1000*60*60*24))} ${aLangKeys[lang]['tpfs_days']}`
    //document.getElementById('time_beratung').innerHTML = `${aLangKeys[lang]['tpfs_use']} ${days}`
    if(Math.floor((date - today) / (1000*60*60*24)) < 60){
        OpenModDialog({type:'warn',title:["custom_protocol_use"],msg:`${days}`,master_btn:['button_ok']})
    }
}

/**
 * The function toSDA redirects the user to a specific page for saddle pressure analysis.
 */
function toSDA(){
  location.pathname = '/production/saddle_pressure_analysis.tcls'
}