
var clients;

function setClients(data){
  clients = data;
}

getEntities('client', setClients);

function initDatagridClients() {
  setClients(null);
  datagridLoading();
  getEntities('client', __initDatagridClients);
}

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

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

  contenu += ' <tbody>';
  clients.forEach(client => {
    contenu += '   <tr class="js-open-modal-trigger" data-modal-info="client:id='+client.idclient+'">';
    contenu += '    <td>'+client.idclient+'</td>';
    contenu += '    <td>'+client.code+'</td>';
    contenu += '    <td>'+client.nom+'</td>';
    contenu += '   </tr>';
  });
  contenu += '  </body>';

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

  element.innerHTML = contenu;

  init_modal();
}

modal_hooks['client'] = 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 client ['+id+']';
      let modal_body='Client inconnu !';
      let modal_footer='<button>Enregistrer</button';
  
      clients.filter(client => client.idclient == id)
        .forEach(resultat => {
          modal_body  = '<table class="modal_table">';
          modal_body += '<tr><td style="width:30%">Id</td><td>'+resultat.idclient+'</td></tr>';
          modal_body += '<tr><td style="width:30%">Code</td><td>'+resultat.code+'</td></tr>';
          modal_body += '<tr><td style="width:30%">Nom</td><td>'+resultat.nom+'</td></tr>';
          modal_body += '</table>';
        });

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