<!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 src="{{ url_for('static', filename='js/jquery-3.6.3.min.js') }}"></script>
<script type="text/javascript" charset="utf-8">
    // All the class come from the Bootstrap v5 documentation and icon also come from bootstrap
    MAX_CARACTERE_DIPLAYED_IN_CONTENT=1000;
    MAX_DISPLAYED_ROW = 500;
      
    var intervalID = null;
    var current_parameters = {};

    function pause() { 
        if (intervalID) {
            clearInterval(intervalID);
            intervalID = null;
            return true;
        } {return false;} ;
    }
      
    function unpause(parameters) {
        if (intervalID) {
            clearInterval(intervalID);
        };
        if (parameters !== undefined) {
          current_parameters = parameters;
        };
        intervalID = setInterval(get_tasks, 5000, current_parameters);
    }
      
    
    //var socket = io();
    //getting param for the filter
    url = new URL(window.location.href); 
    var filter = new Map();
    var windows_open=new Map();
    var paused_task=new Map();
    var detailed_tasks = [];
    color_table='secondary';
    filter.set('sortby',url.searchParams.get('sortby'));
    filter.set('worker',url.searchParams.get('worker'));
    filter.set('status',url.searchParams.get('status'));
    filter.set('batch',url.searchParams.get('batch'));
    filter.set('show',url.searchParams.get('show'));
    sortby='default';
    if(filter.get('sortby')===''||filter.get('sortby')=== null){ var order_by='task';}
    else if(filter.get('sortby')==='worker'){
        order_by='worker';
    }
    else if (filter.get('sortby')==='batch'){
        order_by='batch';
    }
    //Keeping the right color of thead associated with the current tab
    switch(filter.get('show')){
            case 'running':
                color_table='primary';
                break;    
            case 'failed':
                color_table='danger';
                break;
            case 'succeeded':
                color_table='success'
                break;
            case 'terminated': 
                color_table='info';
                break;
            case 'pending': 
                color_table='secondary';
                break;
            default:
                color_table='dark';
        }
    
    //socket.on('connect', function() {
    //    console.log('connecting');
    //    socket.emit('get', {object: 'task', order_by: order_by, filter_by: filter.get('show'), detailed_tasks: detailed_tasks});
    //    });
    
function get_tasks(parameters) {
    //socket.on('task', async function(data){
    
    //some action such as modifying a action needs time to be done so the update of the page can be set on true 
    parameters.object='tasks';
    $.getJSON('/ui/get/', parameters, function(data) {
        //while(pause){
        //    await sleep(5000);
        //};    
        //create a table in a similar way of ui
        tasks= data.tasks;
        console.log('Received tasks', tasks);
        task_table ='<table class="table table-responsive table-hover table-striped"><thead id="task_head" class="text-center table-'+color_table+'"><tr><th>#</th><th>Name</th><th>Command</th><th><div onclick="">Worker</div></th><th>Batch</th><th>Status</th><th>Start</th><th>Runtime</th><th>Output</th><th>Error</th><th>Actions</th></tr></thead></tr></thead>\n<tbody id="table">\n';
        select_worker ='<div> <label class="form-label" for="filter_by_worker">Worker:</label><select id="filter_by_worker" name="worker" class="form-select col-md-3">\n<option value="" '+(filter.get('worker')!=''?'':'')+'>-</option>\n';
        select_batch ='<div> <label class="form-label" for="filter_by_batch">Batch:</label><select id="filter_by_batch" name="batch" class="form-select" col-md-3>\n<option value="" '+(filter.get('batch')!=''?'':'selected')+'>Default</option>\n';
        sort_by='<label for="sortby" class="form-label">Sort by:</label>'
                +'<select id="sortby" name="sortby" class="form-select">'
                +'<option value=""'+(filter.get('sortby')==''?'selected':'')+'>-</option>'
                +'<option value="worker" '+(filter.get('sortby')=='worker'?'selected':'')+'>worker</option>'
                +'<option value="batch" '+(filter.get('sortby')=='batch'?'selected':'')+'> batch</option></select>'
        var list_worker = new Map();
        var list_batch = [];
        running_table='';
        succeeded_table='';
        failed_table='';
        all_table='';

        
        for (i=0 ; i<tasks.length; i++) {
            // list all the workers that 'tasks' contains and set with a Map ( worker_id, worker_name)
            if(tasks[i][10]!==null){
                if(list_worker.has(tasks[i][10].toString()) === false){
                        list_worker.set(tasks[i][10].toString(),tasks[i][2]);
                        select_worker += '<option value="'+tasks[i][10]+'" '+(filter.get('worker')==tasks[i][10].toString()?'selected':'')+'>'+tasks[i][2]+'</option>\n';
                    }
                }
             // list all the batchs that 'tasks' contains
            if((list_batch.includes(tasks[i][3]) === false) && (tasks[i][3] != null)){
                list_batch.push(tasks[i][3]);
                select_batch += '<option value="'+tasks[i][3]+'"'+(filter.get('batch')==tasks[i][3].toString()?'selected':'')+'>'+tasks[i][3]+'</option>\n';
            }
        }
            
        //According to the argument 'show' in the url that others views use, to open the right tab from another view
        switch(filter.get('show')){
            case 'running':
                task_table += create_table('running');
                break;    
            case 'failed':
                task_table += create_table('failed');
                break;
            case 'succeeded':
                task_table += create_table('succeeded');
                break;
            case 'terminated': 
                task_table += create_table('terminated');
                break;
            case 'pending': 
                task_table += create_table('pending');
                break;
            default:
                task_table += create_table('all');
        }

        task_table +='</tbody>\n</table>\n';
        select_worker +='</select>\n</div>';
        select_batch +='</select>\n</div>'
        
        document.getElementById("tasks").innerHTML=task_table;
        document.getElementById("filter_by_worker").innerHTML=select_worker;
        document.getElementById("filter_by_batch").innerHTML=select_batch;
        document.getElementById("sortby").innerHTML=sort_by;
        // Due to the uptade of the page every 5second, This maintain the output to the bottom.
        for(element of document.getElementsByName('scroll')){
            element.scrollTop=999999;
        }
        //await sleep(5000);
        console.log('detailed_tasks: '+detailed_tasks);
        unpause({order_by: order_by, filter_by: filter.get('show'), detailed_tasks: detailed_tasks});
        //    socket.emit('get', {object: 'task', order_by: order_by, filter_by: filter.get('show'), detailed_tasks: detailed_tasks});
        //    });
        //);
    });
}

function remove_from_array(arr, value){
    for( var i = 0; i < arr.length; i++){ 
        if ( arr[i] === value) { 
            arr.splice(i, 1); 
        }
    }
}

//this function allows to change the chevron to the top or to the bottom according to the statement if it is open or not.
function modify_chevron(id_execution,keyword){
    var btn = document.getElementById("chevron-"+keyword+"-"+id_execution.toString());
    if( (btn.value==='false') || (btn.value==='')){
        detailed_tasks.push(id_execution);
        btn.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-up" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M7.646 4.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 5.707l-5.646 5.647a.5.5 0 0 1-.708-.708l6-6z"/></svg>';
        btn.value=true;
        windows_open.set(keyword+'-'+id_execution,'open'); // the displayed content are kept in memory due to the uptade of the page 
        element = document.getElementById("scroll-"+keyword+"-"+id_execution);
        element.scrollTop=999999;
    }      
    else{
        remove_from_array(detailed_tasks,id_execution);
        btn.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-down" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z"/></svg>';
        btn.value=false;
        windows_open.delete(keyword+'-'+id_execution);
    }
}

//Allows to get the right duration of a execution with the suitable unit
function getRuntime(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';
}

//create a table same structure as in ui according to the type of task
function create_table(type_task){
    table='';
    all=false;
    if(type_task ==='all'){
        all=true;
    }
    if (type_task === 'terminated'){
        type_task = ['failed','succeeded'];
    }
    else if(type_task==='running'){
        type_task=['running','paused'];
    }
    else{
        type_task =[type_task];
    }
    j = 0; //count the number of row not to exceed an maximum of row (currently set at 50)
    
    
    // the information go through a filter settled by the arguments in the url that doesn't let it pass if it has not the exact information defined by the filter
    for(i=0;i<tasks.length;i++){
        if((type_task.includes(tasks[i][11])) || all==true){
            if((tasks[i][10]==null?'':tasks[i][10].toString())===filter.get('worker') || filter.get('worker')===null || filter.get('worker')===''){
                if(filter.get('status')===tasks[i][11] ||filter.get('status')===null ||filter.get('status')==='' ){
                    if(filter.get('batch')===tasks[i][3] ||filter.get('batch')===null ||filter.get('batch')===''){
                        j++;
                        var date_started = new Date(tasks[i][4]+"+00");
                        if(tasks[i][11] === 'running'){
                            date_end = new Date();
                        }
                        else{
                            var date_end = new Date(tasks[i][5]+"+00");}
                        var diff_in_second= Math.round((date_end.getTime()- date_started.getTime())/(1000));
                        
                    //Change the color of the status' circle according to the task's status
                    switch(tasks[i][11]){
                        case 'succeeded':
                            task_status = 'success';
                            break;
                        case 'failed':
                            task_status = 'danger';
                            break;
                        case 'running':
                            task_status = 'primary';
                            break;
                        case 'paused':
                            task_status = 'warning';
                            break;
                        case 'pending':
                            task_status='secondary';
                            break;
                        case 'assigned':
                            task_status='secondary';
                            break;
                        case 'accepted':
                            task_status='secondary';
                            break;
                        }
                    table+='<tr><td><h6 class="d-flex col-md-12"><h6>t:'+tasks[i][0]+'</h6><h6> e:'+(tasks[i][6]==null?'':tasks[i][6])
                        +'</h6></td><td width ="5%" class="text-center">'+(tasks[i][1]==null?'':tasks[i][1])
                        +'</td><td class="table-stripped text-center"><div class="btn-group" role="group"><a class="btn btn-outline-secondary border-0 text-dark text-truncate text-center" style="max-width: 10em;" data-bs-toggle="collapse" href="#command-'+tasks[i][6]+'" id ="button-command-'+tasks[i][6]+'"role="button" aria-expanded="false" aria-controls="collapseCommand" onclick="modify_chevron('+tasks[i][6]+',\'command\')">'+tasks[i][9]+'</a><button class="btn btn-outline-secondary border-0 text-dark" data-bs-toggle="collapse" href="#command-'+tasks[i][6]+'" value="'+(windows_open.has('command-'+tasks[i][6])==true?"true":"false")+'" id ="chevron-command-'+tasks[i][6]+'" role="button" aria-expanded="false" aria-controls="collapseCommand" onclick="modify_chevron('+tasks[i][6]+',\'command\')">'+(windows_open.has('command-'+tasks[i][6])==true?'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-up" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M7.646 4.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 5.707l-5.646 5.647a.5.5 0 0 1-.708-.708l6-6z"/></svg>':'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-down" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z"/></svg>')+'</button>'
                        +'</td><td width ="10%" class="text-center">'+(tasks[i][2]==null?'':tasks[i][2])
                        +'</td><td class="text-center">'+(tasks[i][3]==null?'':tasks[i][3])
                        +'</td><td class="text-center text-'+task_status+'" title ="'+tasks[i][11]+'" ><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"class="bi bi-circle-fill " viewBox="0 0 16 16"><circle cx="8" cy="8" r="8"/></svg>'
                        +'</td><td class="text-center">'+(tasks[i][4]==null?'':date_started.getFullYear() + "-" + (date_started.getMonth() + 1) + "-" + date_started.getDate() + " " + date_started.getHours() + ":" + date_started.getMinutes() + ":" + date_started.getSeconds())
                        +'</td><td class="text-center">'+getRuntime(diff_in_second)
                        
                        //The outputs 
                        //the value (a boolean) of the chevron buttons represent the statement of the content
                        +'</td><td class="table-dark text-center">'+(tasks[i][7]==''|| tasks[i][7]==null?'':'<div class="btn-group" role="group"><a class="btn btn-outline-dark border-0 text-white d-inline-block text-truncate text-center" style="max-width: 10em"" data-bs-toggle="collapse" href="#output-std-'+tasks[i][6]+'" role="button" aria-expanded="false" onclick="modify_chevron('+tasks[i][6]+',\'output-std\')" aria-controls="collapseOutput">'+tasks[i][7]
                        +'</a><button class="btn btn-outline-dark border-0 text-white" data-bs-toggle="collapse" href="#output-std-'+tasks[i][6]+'" value="'+(windows_open.has('output-std-'+tasks[i][6])==true?"true":"false")+'" id ="chevron-output-std-'+tasks[i][6]+'" role="button" aria-expanded="false" aria-controls="collapseCommand" onclick="modify_chevron('+tasks[i][6]+',\'output-std\')">'+(windows_open.has('output-std-'+tasks[i][6])==true?'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-up" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M7.646 4.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 5.707l-5.646 5.647a.5.5 0 0 1-.708-.708l6-6z"/></svg>':'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-down" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z"/></svg>')+'</button></div>')
                        +'</td><td class="table-dark text-center">'+(tasks[i][8]=='' || tasks[i][8]==null?'':'<div class="btn-group" role="group"><a class="btn btn-outline-dark border-0 text-warning d-inline-block text-truncate text-center" style="max-width: 10em"" data-bs-toggle="collapse" href="#output-err-'+tasks[i][6]+'" role="button" aria-expanded="false" onclick="modify_chevron('+tasks[i][6]+',\'output-err\')" aria-controls="collapseOutput">'+tasks[i][8]
                        +'</a><button class="btn btn-outline-dark border-0 text-white" data-bs-toggle="collapse" href="#output-err-'+tasks[i][6]+'" value="'+(windows_open.has('output-err-'+tasks[i][6])==true?"true":"false")+'" id ="chevron-output-err-'+tasks[i][6]+'" role="button" aria-expanded="false" aria-controls="collapseCommand" onclick="modify_chevron('+tasks[i][6]+',\'output-err\')">'+(windows_open.has('output-err-'+tasks[i][6])==true?'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-up" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M7.646 4.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 5.707l-5.646 5.647a.5.5 0 0 1-.708-.708l6-6z"/></svg>':'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-down" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z"/></svg>')+'</button></div>')
                        
                        //The actions
                        +'</td><td class="text-center">'+'<div class="btn-group btn-group-sm" role="group" aria-label="Basic mixed styles example">'
                        //the following buttons are shown if the task is running
                        +(tasks[i][11]=='paused'?'<button type="button" title="play" onclick="action_task(\''+tasks[i][0]+'\',\'resume\')" class="btn btn-outline-dark"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-play-circle-fill" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM6.79 5.093A.5.5 0 0 0 6 5.5v5a.5.5 0 0 0 .79.407l3.5-2.5a.5.5 0 0 0 0-.814l-3.5-2.5z"/></svg></button>':'')
                        +(tasks[i][11]=='running'?'<button type="button" title="pause" onclick="action_task(\''+tasks[i][0]+'\',\'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>':'')
                        +(tasks[i][11]=='running'?'<button type="button" title="stop" onclick="displayModal('+i+',\'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>':'')
                        +(tasks[i][11]=='running'?'<button type="button" title="break" onclick="displayModal('+i+',\'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 ="restart" onclick="action_task(\''+tasks[i][0]+'\',\'restart\')" 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 ="download" onclick="download('+tasks[i][0]+','+i+')" class="btn btn-outline-dark"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-download" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg></button>'
                        +'<button type="button" title="delete" onclick="displayModal('+i+',\'delete\')" 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="task-modal-'+tasks[i][6]+'" class="modal"></div>'
                        +'</td></tr>\n'
                        //The contents         //To maintain a displayed content 
                        +'<tr class="collapse '+(windows_open.has('command-'+tasks[i][6])==true?'show':'')+' table" id="command-'+tasks[i][6]+'"><td colspan="11" id="command-content-'+tasks[i][6]+'"><div class="d-flex"><div class="p-2 w-100">'+tasks[i][9]+'</div><div class="p-2 flex-shrink-1"><button type="button" tiltle="modify" onclick="modify_command('+tasks[i][6]+','+i+')" class="btn btn-dark " style="--bs-btn-padding-y: .10rem; --bs-btn-padding-x: .3rem; --bs-btn-font-size: .75rem;">modify</button></div></div></td></tr>'
                        +'<tr class="collapse '+(windows_open.has('output-std-'+tasks[i][6])==true?'show':'')+' table-dark" id="output-std-'+tasks[i][6]+'" ><td colspan="11" class ="border border-light border-5 border-top-0 " ><div name="scroll" id="scroll-output-std-'+tasks[i][6]+'" style="max-height:10em;max-width:100%;white-space: pre-line;" class="overflow-auto">'+(tasks[i][7]==null?'':(tasks[i][7].length>=MAX_CARACTERE_DIPLAYED_IN_CONTENT?tasks[i][7].substring(tasks[i][7].length-1-MAX_CARACTERE_DIPLAYED_IN_CONTENT,tasks[i][7].length-1):tasks[i][7] ))+'</div></td></tr>'
                        +'<tr class="collapse '+(windows_open.has('output-err-'+tasks[i][6])==true?'show':'')+' table-dark" id="output-err-'+tasks[i][6]+'" ><td colspan="11" class ="border border-light border-5 border-top-0 text-warning" ><div name="scroll" id="scroll-output-err-'+tasks[i][6]+'" style="max-height:10em;max-width:100%;white-space: pre-line;" class="overflow-auto">'+(tasks[i][8]==null?'':(tasks[i][8].length>=MAX_CARACTERE_DIPLAYED_IN_CONTENT?tasks[i][8].substring(tasks[i][8].length-1-MAX_CARACTERE_DIPLAYED_IN_CONTENT,tasks[i][8].length-1):tasks[i][8] ))+'</div></td></tr>\n';
                        }
                    }
                    }
            } 
        if(j >= MAX_DISPLAYED_ROW){
            break;
            }
        }
return table;
}

function displayModal(i,type) {
    console.log(document.getElementById('task-modal-'+tasks[i][6]));
    document.getElementById('task-modal-'+tasks[i][6]).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+' task_'+tasks[i][0]+''+(type==='delete'?' ':' execution_'+tasks[i][6])+' ?</p>'
                                                    +'<div class="clearfix"><button type="button" class="btn btn-danger" onclick="document.getElementById(\'task-modal-'+tasks[i][6]+'\').style.display=\''+'none'+'\'; unpause()" >Cancel</button>'
                                                    +'<button type="button" class="btn btn-primary" onclick="action_task(\''+tasks[i][0]+'\',\''+type+'\');document.getElementById(\'task-modal-'+tasks[i][6]+'\').style.display=\''+'none'+'\'; unpause()">Confirm</button></div></div></form>';
    document.getElementById('task-modal-'+tasks[i][6]).style.display = "block";
    pause();
}

function download(id_task,i) {
    var element = document.createElement('a');
    // I used this code https://www.delftstack.com/fr/howto/javascript/javascript-download/ with some modifications
    if (tasks[i][7] !== '' && task[i][7] !== null){
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(tasks[i][7]));
        element.setAttribute('download', 'output-std-'+id_task+'-execution-'+tasks[i][6]);
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
    }
    if (tasks[i][8] !== '' && task[i][8] !== null){
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(tasks[i][8]));
        element.setAttribute('download', 'output-err-'+id_task+'-execution-'+tasks[i][6]);
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
    }
}

// I used the documentation of JSZip
function downloadAll(type){
    var zip = new JSZip();
    for( let i =0 ; i<tasks.length ; i++){
        //the information go through a filter to have the same information that is showed by the view
        console.log(type);
        if(type === tasks[i][11] || type==="all"){
            console.log('1',filter.get('worker'));
            if(filter.get('worker')==(tasks[i][10]==null?'':tasks[i][10].toString())||filter.get('worker')==''||filter.get('worker')==null){
                if(filter.get('batch')==tasks[i][3]||filter.get('batch')==''||filter.get('batch')==null){
                    zip.folder("output-"+tasks[i][0]);
                    if (tasks[i][7] !== '' && task[i][7] !== null){
                        zip.file("output-"+tasks[i][0]+"/output-std-"+tasks[i][0]+"-execution-"+tasks[i][6]+".txt",tasks[i][7]);
                    }
                    if (tasks[i][8] !== '' && task[i][8] !== null){
                        zip.file("output-"+tasks[i][0]+"/output-err-"+tasks[i][0]+"-execution-"+tasks[i][6]+".txt",tasks[i][8]);
                    }
                }
            }
        }
    }
    zip.generateAsync({type:"blob"}).then(function (content) { // 1) generate the zip file
    saveAs(content, "outputs_.zip");
    });
}
        
//Allows to switch betwween the different tabs and change the color of the thead
function show_tasks(type_task){
    document.getElementById("table").innerHTML=create_table(type_task);
    document.getElementById("downloadall").onclick=function() {downloadAll(type_task)};
    windows_open.clear();
    filter.set('show',type_task);
    switch(type_task){
        case'failed':
        color_table='danger';
        break;
        case 'succeeded':
        color_table='success';
        break;
        case 'running':
        color_table='primary';
        break;
        case 'terminated':
        color_table='info';
        break;
        case 'all':
        color_table='dark';
        break;
        case 'pending':
        color_table='secondary';
        break;
    }
    document.getElementById("task_head").className ="text-center table-"+color_table+"";
}

//Send an action to the server
function action_task(t_id,type_action,command){
    if (type_action=='modify'){
        $.ajax({
            url: '/ui/task/action',
            data: {task_id:t_id,action:type_action,modification:command}
        });
    }
    else {
        $.ajax({
            url: '/ui/task/action',
            data: {task_id:t_id,action:type_action}
        });
    }
    console.log('Sending action');
}

//Open a textarea to modify a command.
function modify_command(id_execution,i){
    content = document.getElementById("command-content-"+id_execution);
    if(pause()){
    content.innerHTML='<form><textarea id="textarea-'+id_execution+'"class="form-control" rows="4">'+tasks[i][9]+'</textarea>';
    content.innerHTML+='<button type="button" onclick="modify_command('+id_execution+','+i+')" class="btn btn-danger" style="--bs-btn-padding-y: .10rem; --bs-btn-padding-x: .3rem; --bs-btn-font-size: .75rem;" >Cancel</button><button type="button" class="btn btn-primary" style="--bs-btn-padding-y: .10rem; --bs-btn-padding-x: .3rem; --bs-btn-font-size: .75rem;" onclick="submit_command('+id_execution+','+i+');modify_command('+id_execution+','+i+')">Submit</button></form>';
    }
    else{
    unpause();
    content.innerHTML='<div class="d-flex"><div class="p-2 w-100">'+tasks[i][9]+'</div><div class="p-2 flex-shrink-1"><button type="button" tiltle="modify" onclick="modify_command('+tasks[i][6]+','+i+')" class="btn btn-dark " style="--bs-btn-padding-y: .10rem; --bs-btn-padding-x: .3rem; --bs-btn-font-size: .75rem;">modify</button></div>';
    }
}

//the function required to be set after the texte area so it can get the value of it
function submit_command(id_execution,i){
    return action_task(tasks[i][0],'modify',document.getElementById('textarea-'+id_execution).value);
}

function pause_page(){
    if (pause()) {
        document.getElementById('pause').innerHTML='Pause';
    } {
        unpause();
        document.getElementById('pause').innerHTML='Resume';
    }
}

$(document).ready( get_tasks( {} ) );
</script>
</head>
<body>
    <title>Tasks view</title>
    <img src={{ url_for("static", filename="favicon.png") }} width=64px style="float:left; margin-bottom:2px;"/>
    <h1 style="float:left;">Tasks view</h1>
    <div class="container" style="margin-bottom: -37px; max-width: 100%">
        <div class="row">
            <div class="col-md-7" style="float:left;">
                
                <form class="row g-2">
                    <h3 class="col-md-2 p-2">Filter</h3>
                    <div class="p-2 col-md-2">
                        <label for="sortby" id="sortby" class="form-label">Sort by:</label>
                    </select>
                    </div>
                    <p class="col-md-2 p-2" id="filter_by_worker"></p>
                    <p class="col-md-2 p-2" id="filter_by_batch"></p>

                    <div class="align-self-center p-2 col-md-2" style="margin-top: 23px;">
                      <button class="btn btn-primary " type="submit">Apply</button>
                    </div>
                  </form> 
                </div>
            <div class="col-md-5">
                <div class="d-flex" role="group" aria-label="Basic mixed styles example">
                    <h3 class=" p-2"> Action</h3>
                    <div class="btn-group" role="group"></div>
                    <button type="button" id="pause" onclick="pause_page()" class="btn btn-warning"> Pause </button>
                    <button type="button" id="downloadall" onclick="downloadAll('all')"  class="btn btn-info">Download All<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-download" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg></button>
                    <a type="button" id="downloadall" target="_blank" href="/ui/batch/"  class="btn btn-secondary d-flex align-items-center">Batch view</a>
                    <p style='float:right; margin:0.5em;border-width: 1px;border-color: grey;background-color: lightgrey;padding:0.3em;max-height:2.5em;border-style: double;font-size:small'>v{{ package_version }} </p>
                    </div>
                </div>
                </div>
             </div>    
        </div> 
    </div>

<br/>
<ul class="nav nav-tabs">
    <li class="nav-item">
        <input  class="nav-link bg-dark text-white" href="#" id="nav_all" type="button" onclick="show_tasks('all')" id ="all_tasks" value="All">
    </li>
    <li class="nav-item">
        <input  class="nav-link bg-secondary text-white" href="#" id="nav_all" type="button" onclick="show_tasks('pending')" id ="pending_tasks" value="Pending tasks">
    </li>   
    <li class="nav-item">
    <input  class="nav-link bg-primary text-white" href="#" id="nav_running" type="button" onclick="show_tasks('running')" id ="running_tasks" value="Running tasks">
    </li>  
    <li class="nav-item">  
    <input class="nav-link bg-info text-dark" href="#"  id="nav_terminated" type="button" onclick="show_tasks('terminated')" id ="terminated_tasks" value="Terminated tasks">
    </li>
    <li class="nav-item">
    <input class="nav-link bg-success text-dark" href="#" id="nav_succeeded" type="button" onclick="show_tasks('succeeded')" id="succeeded_tasks" value="Succeeded tasks">
    </li>
    <li class="nav-item"> 
    <input class="nav-link bg-danger text-dark" href="#" id="nav_failed" type="button" onclick="show_tasks('failed')" id="failed_tasks" value="Failed tasks">
    </li>
</ul>
<div class="col-md-12">
    <div class="panel panel-default">
      <span id="tasks"> Loading please wait... </span>
    </div>
  </div>
  <div class="clearfix"></div>
  <br /><br />
    </div>
</body>

  

  


