<!doctype html>

<head>
  <link rel="icon" type="image/png" href={{ url_for("static", filename="favicon.png") }}>
  <link href={{ url_for("static", filename="css/bootstrap.v5.0.2/bootstrap.min.css") }} rel="stylesheet">
  <script src={{ url_for("static", filename="js/bootstrap.v5.0.2/bootstrap.min.js") }}></script>
  <script src={{ url_for("static", filename="js/FileSaver.v2.0.4/FileSaver.min.js") }}></script>
  <script src={{ url_for("static", filename="js/jszip.min.v3.10.0.js") }}></script>
  <script src={{ url_for("static", filename="js/socket.io.v4.0.1/socket.io.js") }}></script>
  <script type="text/javascript" charset="utf-8">
    // All the class come from the Bootstrap v5 documentation and icon also come from bootstrap
   const delay = ms => new Promise(res => setTimeout(res, ms));
    function sleep (time) {
        return new Promise((resolve) => setTimeout(resolve, time));
      }
    pause=false;
    var socket = io();
    socket.on('connect', function() {
        console.log('connecting');
        socket.emit('get', {object: 'batch'});
        });
        

    socket.on('batch', async function(data){
      //some action such as modify a action needs time to be done so the update of the page can be set on true 
      while(pause){
        await delay(5000);
      }
        batches= data.batches;
        workers=data.workers;
        console.log('Received batches', batches);
        console.log('Received workers', workers);
        batch_table ='<table class="table table-responsive table-hover table-striped text-center "><thead class="text-center table-secondary"><tr><th>#</th><th>Name</th><th>Workers</th><th>Progress</th><th>pending</th><th>running</th><th>successes</th><th>failed</th><th>total</th><th>Average duration [min - max] </th><th>Actions</th></tr></thead>\n<tbody id="table">\n';
        list_batch=[];
        workers_by_batch =new Map();
        // list al the worker in batches
        for(i = 0; i < workers.length; i++){
          batch_name = workers[i][0];
          workers_by_batch.set(batch_name,workers[i][1].replaceAll(',','<br/>'));
        }
        for(i=0; i<batches.length;i++){
          //list all the batch
          if(list_batch.includes(batches[i][0])===false){
            list_batch.push(batches[i][0]);
            current_batch=batches[i][0];
          }
          //for one row is associated to a batch and a loop while, all the information dealing with the current batch are picked up 
          total=0;
          status_running=0;
          status_failed=0;
          status_pending=0;
          status_succeeded=0;
          stat_details='';
          status_paused=0;
          while(current_batch === batches[i][0]){
            status = batches[i][1];
            count = batches[i][2];
            duration_max = batches[i][3];
            duration_min = batches[i][4];
            duration_avg = batches[i][5];

            total += count;
            if (['running','paused'].includes(status)) {status_running+=count;}
            else if (['pending','accepted'].includes(status)) {status_pending+=count;}
            else if (status==='succeeded') {status_succeeded+=count;}
            else if (status==='failed') {status_failed+=count;}
            if (duration_avg!==null) {
              stat_details += '<div class="p-2 text-'
                +(status==='succeeded'?'success':status==='failure'?'danger':'normal')
                +'">'+status+': '+duration_avg.toFixed(2)
                +' ['+ duration_min.toFixed(2) 
                +' - '+ duration_max.toFixed(2)+']</div>';
            }


            i++;
            if(i===batches.length){break;} 
          }
          real_batch=current_batch;
          if (current_batch==null) {current_batch='Default';}
          batch_table +='<tr><td>'
                    +'</td><td width ="5%">'+'<a type="button" class="btn btn-outline-dark border-0" target="_blank" href="/ui/task/?sortby=&worker=&batch='+current_batch.replace(' ','+')+'">'+current_batch+'</a>'
                    +'</td><td style="vertical-align: middle;">'+workers_by_batch.get(real_batch)
                    +'</td><td ><div class="progress border-1" style="margin-top:10px;"><div class="progress-bar'+(status_running==0?'':' progress-bar-striped progress-bar-animated')+' bg-danger" role="progressbar" style="width:'+status_failed/total*100+'%" aria-valuenow="'+status_failed/total*100+'" aria-valuemin="0" aria-valuemax="100"></div><div class="progress-bar '+(status_running==0?'':' progress-bar-striped progress-bar-animated')+' bg-success" role="progressbar" style="width:'+status_succeeded/total*100+'%" aria-valuenow="24" aria-valuemin="0" aria-valuemax="100"></div></div>'
                    +'</td><td width ="10%" style="padding-top: 14px;">'+status_pending
                    +'</td><td >'+'<a type="button" class="btn btn-outline-dark border-0" target="_blank" href="/ui/task/?sortby=&worker=&batch='+current_batch.replace(' ','+')+'&show=running">'+status_running+'</a>'
                    +'</td><td >'+'<a type="button" class="btn btn-outline-dark border-0" target="_blank" href="/ui/task/?sortby=&worker=&batch='+current_batch.replace(' ','+')+'&show=succeeded">'+status_succeeded+'</a>'
                    +'</td><td >'+'<a type="button" class="btn btn-outline-dark border-0" target="_blank" href="/ui/task/?sortby=&worker=&batch='+current_batch.replace(' ','+')+'&show=failed">'+status_failed+'</a>'
                    +'</td><td >'+'<a type="button" class="btn btn-outline-dark border-0" target="_blank" href="/ui/task/?sortby=&worker=&batch='+current_batch.replace(' ','+')+'">'+total+'</a>'
                    +'</td><td>'+stat_details
                    +'</td><td><div class="btn-group">'
                    +'<button type="button" title="simple pause" onclick="displayModal(\''+current_batch+'\',\'pause\')" class="btn btn-outline-dark"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pause-circle-fill" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM6.25 5C5.56 5 5 5.56 5 6.25v3.5a1.25 1.25 0 1 0 2.5 0v-3.5C7.5 5.56 6.94 5 6.25 5zm3.5 0c-.69 0-1.25.56-1.25 1.25v3.5a1.25 1.25 0 1 0 2.5 0v-3.5C11 5.56 10.44 5 9.75 5z"/></svg></button>'
                    +'<button type="button" title="go" onclick="displayModal(\''+current_batch+'\',\'go\',\''+status_paused+'\')" class="btn btn-outline-dark"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-bootstrap-reboot" viewBox="0 0 16 16"><path d="M1.161 8a6.84 6.84 0 1 0 6.842-6.84.58.58 0 1 1 0-1.16 8 8 0 1 1-6.556 3.412l-.663-.577a.58.58 0 0 1 .227-.997l2.52-.69a.58.58 0 0 1 .728.633l-.332 2.592a.58.58 0 0 1-.956.364l-.643-.56A6.812 6.812 0 0 0 1.16 8z"/><path d="M6.641 11.671V8.843h1.57l1.498 2.828h1.314L9.377 8.665c.897-.3 1.427-1.106 1.427-2.1 0-1.37-.943-2.246-2.456-2.246H5.5v7.352h1.141zm0-3.75V5.277h1.57c.881 0 1.416.499 1.416 1.32 0 .84-.504 1.324-1.386 1.324h-1.6z"/></svg></button>'
                    +'<button type="button" title="stop" onclick="displayModal(\''+current_batch+'\',\'stop\')" class="btn btn-outline-dark"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x-circle" viewBox="0 0 16 16"><path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/><path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/></svg></button>'
                    +'<button type="button" title="break" onclick="displayModal(\''+current_batch+'\',\'break\')" class="btn btn-outline-dark"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-exclamation-lg" viewBox="0 0 16 16"><path d="M7.005 3.1a1 1 0 1 1 1.99 0l-.388 6.35a.61.61 0 0 1-1.214 0L7.005 3.1ZM7 12a1 1 0 1 1 2 0 1 1 0 0 1-2 0Z"/></svg></button>'
                    +'<button type="button" title="clear" onclick="displayModal(\''+current_batch+'\',\'clear\')" class="btn btn-outline-dark"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-eraser" viewBox="0 0 16 16"><path d="M8.086 2.207a2 2 0 0 1 2.828 0l3.879 3.879a2 2 0 0 1 0 2.828l-5.5 5.5A2 2 0 0 1 7.879 15H5.12a2 2 0 0 1-1.414-.586l-2.5-2.5a2 2 0 0 1 0-2.828l6.879-6.879zm2.121.707a1 1 0 0 0-1.414 0L4.16 7.547l5.293 5.293 4.633-4.633a1 1 0 0 0 0-1.414l-3.879-3.879zM8.746 13.547 3.453 8.254 1.914 9.793a1 1 0 0 0 0 1.414l2.5 2.5a1 1 0 0 0 .707.293H7.88a1 1 0 0 0 .707-.293l.16-.16z"/></svg></button></div>'
                    +'<div id="batch-modal-'+current_batch+'" class="modal"></div>'
                    +'</td></tr>\n';
          
          i--;
        }
        batch_table +='</tbody>\n</table>\n';
        document.getElementById("batches").innerHTML=batch_table; 
        await delay(5000);
        socket.emit('get', {object:'batch'});
    });
      function displayModal(current_batch,type,status_paused=0) {
            //Status is only used with type = go.
            console.log(document.getElementById('batch-modal-'+current_batch));
            if(type==='pause'||type==='go'){
              document.getElementById('batch-modal-'+current_batch).innerHTML='<div class="modal-dialog modal-dialog-centered"><form class="modal-content"><div class="container"><h3>'+type+'</h3><p> Do you want to '+(type==='go'?'start/restart the batch ' : type +' the batch' ) +' '+current_batch+' '+(type==='go'?'and resume the tasks in pause ('+status_paused+') ?':'and the tasks in progress ?')+'</p>'
                                                                    +'<div class="clearfix"><button type="button" class="btn btn-danger" onclick="document.getElementById(\'batch-modal-'+current_batch+'\').style.display=\''+'none'+'\'; pause = false" >Cancel</button>'
                                                                    +'<button type="button" class="btn btn-warning" onclick="action_batch(\''+current_batch+'\',\''+type+'\');document.getElementById(\'batch-modal-'+current_batch+'\').style.display=\''+'none'+'\'; pause = false">Both</button>'
                                                                    +'<button type="button" class="btn btn-primary" onclick="action_batch(\''+current_batch+'\',\'simple '+type+'\');document.getElementById(\'batch-modal-'+current_batch+'\').style.display=\''+'none'+'\'; pause = false">Only Batch</button></div></div></form>';
            }
            else{
            document.getElementById('batch-modal-'+current_batch).innerHTML='<div class="modal-dialog modal-dialog-centered"><form class="modal-content"><div class="container"><h3>'+type+'</h3><p>Are you sure you want to '+type+' '+current_batch+' ?</p>'
                                                                    +'<div class="clearfix"><button type="button" class="btn btn-danger" onclick="document.getElementById(\'batch-modal-'+current_batch+'\').style.display=\''+'none'+'\'; pause = false" >Cancel</button>'
                                                                    +'<button type="button" class="btn btn-primary" onclick="action_batch(\''+current_batch+'\',\''+type+'\');document.getElementById(\'batch-modal-'+current_batch+'\').style.display=\''+'none'+'\'; pause = false">Confirm</button></div></div></form>';
            }
            document.getElementById('batch-modal-'+current_batch).style.display = "block";
            pause=true;
        }
      function getAvg(diff_in_second){
        if (diff_in_second>3600*24) {
            return [(diff_in_second/(3600*24)).toFixed(1),'d'];
        }
        else if(diff_in_second>3600){
          return [(diff_in_second/3600).toFixed(1),'h'] ;
        }
        else if(diff_in_second>60){
          return [(diff_in_second/60).toFixed(1),'min'];
            }
      return [(diff_in_second).toFixed(1),'s'];
      }
      function getDiffMax(diff_min,diff_maxi,unit){
        if(diff_min>diff_maxi){diff=diff_min;}
        else{diff=diff_maxi;}
        switch(unit){
          case'd':
          return (diff/(24*3600)).toFixed(1);
          case'h':
          return (diff/(3600)).toFixed(1);
          case'min':
          return (diff/(60)).toFixed(1);
          case's':
          return (diff).toFixed(1);
        }
      }
      //Send an action to the server
      function action_batch(batch_name,action,signal=0){
        socket.emit('batch_action',{action : action, name:batch_name, signal:signal});
        console.log('Sending action',{action : action, name:batch_name, signal:signal});
        }
</script>
</head>
<body style="margin-top:-16px;">
  <title>batches view</title>
  <img src={{ url_for("static", filename="favicon.png") }} width=64px style="float:left; margin-bottom:2px;"/><h1 style="float:left;">batches view</h1>
    <div class="container">
        <div class="">
      
        <p class="col-md-3" id="select"></p>
                  
                  
        </div> 
    </div>


<div class="col-md-12">
    <div class="panel panel-default">
      <span id="batches"> Loading please wait... </span>
    </div>
  </div>

  <div class="clearfix"></div>
  <br /><br />
    </div>
  
</body>

  

  


