{% extends "base.html" %}

{% autoescape None %}

{% block title %}Task {{ task['task_index'] }}, Dataset {{ dataset['dataset'] }} - IceProd{% end %}

{% block page_title %}Task Details{% end %}

{% block body %}

<div class="task_details">
{% for k in task %}
<div class="key_value">
  <div>{{ escape(k) }}</div>
  <div>
  {% if k == 'dataset_id' %}
    <a href="/dataset/{{ url_escape(task[k]) }}">{{ escape(task[k]) }}</a>
  {% elif k == 'job_id' %}
    <a href="/dataset/{{ url_escape(task['dataset_id']) }}/job/{{ url_escape(task[k]) }}">{{ escape(task[k]) }}</a>
  {% elif k == 'depends' %}
    {% for t in task[k] %}
        <a href="/dataset/{{ url_escape(task['dataset_id']) }}/task/{{ t }}">{{ escape(t) }}</a>&nbsp;&nbsp;
    {% end %}
  {% else %}
    {{ task[k] }}
  {% end %}
  </div>
</div>
{% end %}

{% if (current_user) %}
<div class="action">
    <button onclick='task_reset();'>Reset</button></td>
    <button onclick='task_hard_reset();'>Hard Reset</button></td>
    <button onclick='task_suspend();'>Suspend</button></td>
    <button onclick='delete_task_logs();'>Delete Logs</button></td>
</div>
{% end %}

</div>

{% if task_stats %}
<div class="task_stats">
  <p class="stat_name">task stats</p>
  <div class="stat_body">{{ '<br />'.join(escape(json_encode(task_stats, indent=2).replace('\r','')).replace(' ','&nbsp;').split('\n')) }}</div>
</div>
{% end %}

<section class="logs">
{% if 'stdlog' in logs %}
  <div class="logs">
    <span class="log_name"><a href='/dataset/{{ url_escape(task['dataset_id']) }}/log/{{ url_escape(logs['stdlog'][0]['log_id']) }}'>stdlog</a></span>
    {% for i,log in enumerate(logs['stdlog'][1:10]) %}
        <span class="log_link"><a href='/dataset/{{ url_escape(task['dataset_id']) }}/log/{{ url_escape(log['log_id']) }}'>{{ i+2 }}</a></span>
    {% end %}
    {% if len(logs['stdlog']) > 10 %}
        <span class="log_extra"> (+ {{ len(logs['stdlog'])-10 }} more)</span>
    {% end %}
    {% if not (('stdout' in logs and logs['stdout'][0]['data']) or ('stderr' in logs and logs['stderr'][0]['data'])) %}
    <div class="log_body">{{ '<br />'.join(map(escape,logs['stdlog'][0]['data'].replace('\r','').split('\n')[-20:])) }}</div>
    {% end %}
  </div>
{% end %}
{% if 'stdout' in logs %}
  <div class="logs">
    <span class="log_name"><a href='/dataset/{{ url_escape(task['dataset_id']) }}/log/{{ url_escape(logs['stdout'][0]['log_id']) }}'>stdout</a></span>
    {% for i,log in enumerate(logs['stdout'][1:10]) %}
        <span class="log_link"><a href='/dataset/{{ url_escape(task['dataset_id']) }}/log/{{ url_escape(log['log_id']) }}'>{{ i+2 }}</a></span>
    {% end %}
    {% if len(logs['stdout']) > 10 %}
        <span class="log_extra"> (+ {{ len(logs['stdout'])-10 }} more)</span>
    {% end %}
    <div class="log_body">{{ '<br />'.join(map(escape,logs['stdout'][0]['data'].replace('\r','').split('\n')[-20:])) }}</div>
  </div>
{% end %}
{% if 'stderr' in logs %}
  <div class="logs">
    <span class="log_name"><a href='/dataset/{{ url_escape(task['dataset_id']) }}/log/{{ url_escape(logs['stderr'][0]['log_id']) }}'>stderr</a></span>
    {% for i,log in enumerate(logs['stderr'][1:10]) %}
        <span class="log_link"><a href='/dataset/{{ url_escape(task['dataset_id']) }}/log/{{ url_escape(log['log_id']) }}'>{{ i+2 }}</a></span>
    {% end %}
    {% if len(logs['stderr']) > 10 %}
        <span class="log_extra"> (+ {{ len(logs['stderr'])-10 }} more)</span>
    {% end %}
    <div class="log_body">{{ '<br />'.join(map(escape,logs['stderr'][0]['data'].replace('\r','').split('\n')[-20:])) }}</div>
  </div>
{% end %}
{% for name in logs %}
  {% if name not in ('stdlog', 'stdout', 'stderr') %}
  <div class="logs">
    <span class="log_name"><a href='/dataset/{{ url_escape(task['dataset_id']) }}/log/{{ url_escape(logs[name][0]['log_id']) }}'>{{ escape(name) }}</a></span>
    {% for i,log in enumerate(logs[name][1:10]) %}
        <span class="log_link"><a href='/dataset/{{ url_escape(task['dataset_id']) }}/log/{{ url_escape(log['log_id']) }}'>{{ i+2 }}</a></span>
    {% end %}
    {% if len(logs[name]) > 10 %}
        <span class="log_extra"> (+ {{ len(logs[name])-10 }} more)</span>
    {% end %}
    <div class="log_body">{{ '<br />'.join(map(escape,logs[name][0]['data'].replace('\r','').split('\n')[-10:])) }}</div>
  </div>
  {% end %}
{% end %}
</section>

{% end %}

{% block body_scripts %}

{% if (current_user) %}
<script type="text/javascript" src="/static/fetch.js"></script>
<script type="text/javascript" src="/static/rest.js"></script>
<script>
var rest_api = '{{ rest_api }}';
const passkey = "{{ passkey }}";
const dataset_id = "{{ task['dataset_id'] if task else '' }}";
const job_id = "{{ task['job_id'] if task else '' }}";
const task_id = "{{ task['task_id'] if task else '' }}";

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function service_worker(action) {
    try {
        const url = '/actions/task_status';
        const args = {
            dataset_id: dataset_id,
            action: action,
            task_ids: [task_id],
        };
        const ret = await fetch_json('POST', url, args, passkey);
        if ('error' in ret) {
            message_alert('error - '+ret['error']);
            return false;
        }
        const id = ret['result'];

        while (true) {
            await sleep(1000);
            const url = '/actions/task_status/'+id;
            const ret = await fetch_json('GET', url, null, passkey);
            if (ret['status'] == 'error') {
                if ('error_message' in ret) {
                    message_alert('error - '+ret['error_message']);
                } else {
                    message_alert('error - '+action+' failed');
                }
                return false;
            } else if (ret['status'] == 'complete') {
                message('complete');
                break;
            } else if ('payload' in ret && 'progress' in ret['payload']) {
                message('progress - '+ret['payload']['progress']+'%')
            }
        }
    } catch(err) {
        message_alert('error - '+err);
        return false;
    }
    reload();
    return true;
}

async function task_reset() {
    return await service_worker('reset')
}

async function task_hard_reset() {
    return await service_worker('hard_reset')
}

async function task_suspend() {
    return await service_worker('suspend')
}

async function delete_task_logs() {
    try {
        const url = '/datasets/' + dataset_id + '/task/' + task_id + '/logs';
        const ret = await fetch_json('DELETE', url, {}, passkey);
        if ('error' in ret) {
            message_alert('error - '+ret['error']);
            return false;
        }
    } catch(err) {
        message_alert('error - '+err);
        return false;
    }
    reload();
    return true;
}
</script>
{% end %}

{% end %}
