
var allStatus;

function getStatusLibelleFromId(idstatus){
  let filtre = allStatus.filter(status => status.idstatus == idstatus);
  return (filtre[0]?.libelle ?? "Inconnu");
}

function setStatus(data){
  allStatus = data;
}

getEntities('status', setStatus);

function initDatagridStatus() {
  setStatus(null);
  datagridLoading();
  getEntities('status', __initDatagridStatus);
}

function __initDatagridStatus(data) {
  let element = document.querySelector('#datagrid');
  let contenu='';
  
  setStatus(data);

  contenu += '<table>';
  contenu += ' <thead>';
  contenu += '   <tr>';
  contenu += '    <th>Id</th>';
  contenu += '    <th>Status</th>';
  contenu += '   </tr>';
  contenu += '  </thead>';

  contenu += ' <tbody>';
  allStatus.forEach(status => {
    contenu += '   <tr class="js-open-modal-trigger" data-modal-info="status:id='+status.idstatus+'">';
    contenu += '    <td>'+status.idstatus+'</td>';
    contenu += '    <td>'+status.libelle+'</td>';
    contenu += '   </tr>';
  });
  contenu += '  </body>';

  contenu += ' <tfoot>';
  contenu += '   <tr>';
  contenu += '    <th colspan="2">&nbsp;</th>';
  contenu += '   </tr>';
  contenu += '  </foot>';
  contenu += '</table>';

  element.innerHTML = contenu;

  init_modal();
}

modal_hooks['status'] = function(parametres){
  let paramSplit = parametres.split(',');
  paramSplit.forEach(element => {
    let elemSplit=element.split('=');
    if (elemSplit[0] === 'id') {
      let id = elemSplit[1];
      let modal_header='Fiche status ['+id+']';
      let modal_body='status inconnu !';
      let modal_footer='<button>Enregistrer</button';
  
      statuss.filter(status => status.idstatus == id)
        .forEach(resultat => {
          modal_body  = '<table class="modal_table">';
          modal_body += '<tr><td style="width:30%">Id</td><td>'+resultat.idstatus+'</td></tr>';
          modal_body += '<tr><td style="width:30%">Code</td><td>'+resultat.libelle+'</td></tr>';
          modal_body += '</table>';
        });

      modalSetHeader(modal_header);
      modalSetBody(modal_body);
      modalSetFooter(modal_footer);   
    }
  });
};