<?php

/**
 *
 * bareos-webui - Bareos Web-Frontend
 *
 * @link      https://github.com/bareos/bareos for the canonical source repository
 * @copyright Copyright (C) 2013-2023 Bareos GmbH & Co. KG (http://www.bareos.org/)
 * @license   GNU Affero General Public License (http://www.gnu.org/licenses/)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

$title = 'Jobs';
$this->headTitle($title);

?>

<ul class="nav nav-tabs">
   <li><a href="<?php echo $this->url('job', array('action'=>'index')); ?>"><?php echo $this->translate('Show'); ?></a></li>
   <li><a href="<?php echo $this->url('job', array('action'=>'actions')); ?>"><?php echo $this->translate('Actions'); ?></a></li>
   <li><a href="<?php echo $this->url('job', array('action'=>'run')); ?>"><?php echo $this->translate('Run'); ?></a></li>
   <li class="active"><a href="<?php echo $this->url('job', array('action'=>'rerun')); ?>"><?php echo $this->translate('Rerun'); ?></a></li>
   <li><a href="<?php echo $this->url('job', array('action'=>'timeline')); ?>"><?php echo $this->translate('Timeline'); ?></a></li>
</ul>

<br />

<?php if($this->acl_alert) : echo $this->ACLAlert($this->invalid_commands); elseif(!$this->acl_alert) : ?>

<div class="row">

   <div class="col-md-9">

      <div class="panel panel-default">

         <div class="panel-heading">
            <h3 class="panel-title"><?php echo $this->translate('Rerun Jobs'); ?></h3>
         </div>

         <div class="panel-body">

         <p><div class="col-md-12"><input id="rangeslider" style="width: 25%;"></div></p>

         <table class="table table-no-bordered table-hover"
            id="jobtable"
            data-toolbar=".job-table-toolbar"
            data-toolbar-align="right"
            data-filter-control="true">

         <thead class="bg-primary">
            <th></th>
            <th
               data-field="jobid"
               data-width="150">
               <?php echo $this->translate("Job ID"); ?>
            </th>
            <th
               data-field="name">
               <?php echo $this->translate("Job name"); ?>
            </th>
            <th
               data-field="client">
               <?php echo $this->translate("Client"); ?>
            </th>
            <th
               data-field="type"
               data-width="50">
               <?php echo $this->translate("Type"); ?>
            </th>
            <th
               data-field="level"
               data-width="50">
               <?php echo $this->translate("Level"); ?>
            </th>
            <th
               data-field="starttime"
               data-width="200">
               <?php echo $this->translate("Start"); ?>
            </th>
            <th
               data-field="endtime"
               data-width="200">
               <?php echo $this->translate("End"); ?>
            </th>
            <th
               data-field="joberrors"
               data-width="50">
               <?php echo $this->translate("Errors"); ?>
            </th>
            <th
               data-field="jobstatus"
               data-width="150">
               <?php echo $this->translate("Status"); ?>
            </th>
         </thead>

         </table>

         <div id="custom-toolbar">
            <br /><br />
            <button id="button" class="btn btn-primary" onclick="rerunJobs()">Rerun</button>
            <br /><br />
         </div>

         </div>
      </div>

   </div>

   <div class="col-md-3">
      <div class="panel panel-default">
         <div class="panel-heading">
            <h3 class="panel-title"><?php echo $this->translate('Director Messages'); ?></h3>
         </div>
         <div class="panel-body">
            <pre class="dird-messages" id="dir-messages" style="height: 600px; font-size: 8pt;"></pre>
         </div>
      </div>
   </div>

</div>

<!-- modal-001 start -->
<div id="modal-001" class="modal fade modal-001" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
  <div class="modal-dialog modal-md">
    <div class="modal-content">
   <div class="modal-header">
   <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
   <h4 class="modal-title" id="myModalLabel"><?php echo $this->translate("Failed to retrieve data from Bareos director"); ?></h4>
      </div>
      <div class="modal-body">
   <p><?php echo $this->translate("Please try to reduce the amount of data to display."); ?></p>
   <p><?php echo $this->translate("Error message received from director:"); ?></p>
   <p class="text-danger"><?php echo $this->translate("Failed to send result as json. Maybe the result message is too long?"); ?></p>
      </div>
      <div class="modal-footer">
         <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo $this->translate("Close"); ?></button>
      </div>
    </div>
  </div>
</div>
<!-- modal-001 end -->

<!-- modal-004 start -->
<div id="modal-004" class="modal fade modal-004" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel2">
   <div class="modal-dialog modal-sm">
   <div class="modal-content">
      <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"></h4>
      </div>
      <div class="modal-body">
         <p><?php echo $this->translate("Please select at least one job."); ?></p>
      </div>
      <div class="modal-footer">
         <button id="modal-004-btn-ok" type="button" class="btn btn-primary" data-dismiss="modal"><?php echo $this->translate("OK"); ?></button>
      </div>
   </div>
   </div>
</div>
<!-- modal-004 end -->

<?php
   echo $this->headScript()->prependFile($this->basePath() . '/js/custom-functions.js');
   echo $this->headLink()->prependStylesheet($this->basePath() . '/css/bootstrap-slider.min.css');
   echo $this->headLink()->prependStylesheet($this->basePath() . '/css/bootstrap-table.min.css');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-slider.min.js');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-table-formatter.js');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-table-locale-all.min.js');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-table-cookie.min.js');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-table.min.js');
?>

<script>

   var basePath = "<?php echo $this->basePath(); ?>";
   var displayRange = 1;

   var rsLabel1 = "1 " + iJS._("day");
   var rsLabel2 = "3 " + iJS._("days");
   var rsLabel3 = "7 " + iJS._("days");
   var rsLabel4 = "14 " + iJS._("days");
   var rsLabel5 = "31 " + iJS._("days");

   var rangeslider = $("#rangeslider").bootstrapSlider({
      ticks: [1,3,7,14,31],
      ticks_labels: [rsLabel1, rsLabel2, rsLabel3, rsLabel4, rsLabel5],
      ticks_positions: [0,25,50,75,100],
      step: 1,
      lock_to_ticks: true,
      tooltip: "hide",
      handle: "round",
      value: displayRange
   });

   function getSliderValue() {
      let range = document.getElementById("rangeslider");
      displayRange = range.value;
      $("#rangeValue").html(displayRange);
      refreshTableData();
   }

   function refreshTableData() {
      $('#spinner').fadeIn('slow');
      $('#jobtable').bootstrapTable('refreshOptions', {
         url: '<?php echo $this->url('api/job', array(), array()) . '?filter=rerun&period='; ?>' + displayRange,
      });
      $('#spinner').fadeOut('slow');
   }

   function rerunJobs() {

      let selection = $('#jobtable').bootstrapTable('getSelections');

      const jobs = [];

      selection.forEach(function(element) {
         jobs.push(element.jobid);
      });

      let s = jobs.join();

      if (s.length === 0) {
        $("#modal-004").modal();
      } else {
         let url = "<?php echo $this->url('api/execute', array(), array()) . '?command=rerun&jobs=" + s + "'; ?>";

         $('#dir-messages').empty()

         $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            timeout: 10000,
            success: function(data) {
               data.forEach((item) => {
                  $('#dir-messages').append('<p>' + item + '</p>')
               })
            },
            error: function() {
               console.log('Error fetching data.')
            },
            timeout: function() {
               console.log('Timeout fetching data.')
            },
            parsererror: function() {
               console.log('Error parsing data.')
            }
         });
      }
   }

   function attachJobTable() {
      $('#jobtable').bootstrapTable({
         locale: '<?php echo str_replace('_','-', $_SESSION['bareos']['locale']); ?>',
         cookie: <?php echo $_SESSION['bareos']['dt_statesave']; ?>,
         cookieIdTable: 'jobs_rerun',
         url: '<?php echo $this->url('api/job', array(), array("query" => array("rerun" => "rerun"))) . '&period='; ?>' + displayRange,
         method: 'get',
         dataType: 'json',
         pagination : false,
         sidePagination: 'client',
         pageList: [ <?php echo $_SESSION['bareos']['dt_lengthmenu']; ?> ],
         pageSize: <?php echo $_SESSION['bareos']['dt_pagelength']; ?>,
         search: true,
         searchAlign: 'left',
         showPaginationSwitch: false,
         showRefresh: false,
         sortName: 'jobid',
         sortOrder: 'desc',
         checkboxHeader: true,
         clickToSelect: true,
         virtualScroll: true,
         height: 600,
         columns: [
            {
               field: 'state',
               checkbox: true
            },
            {
               field: 'jobid',
               sortable: true,
               formatter: function(value) {
                  return formatJobId(value, basePath);
               }
            },
            {
               field: 'name',
               sortable: true,
               formatter: function(value) {
                  return formatJobName(value, basePath, displayRange);
               }
            },
            {
               field: 'client',
               sortable: true,
               formatter: function(value) {
                  return formatClientName(value, basePath);
               }
            },
            {
               field: 'type',
               sortable: true,
               formatter: function(value) {
                  return formatJobType(value);
               }
            },
            {
               field: 'level',
               sortable: true,
               formatter: function(value) {
                  return formatJobLevel(value);
               }
            },
            {
               field: 'starttime',
               sortable: true
            },
            {
               field: 'endtime',
               sortable: true
            },
            {
               field: 'joberrors',
               sortable: true,
            },
            {
               field: 'jobstatus',
               sortable: true,
               formatter: function(value) {
                  return formatJobStatus(value);
               }
            }
         ]
      });
   }

   $(document).ready(function() {

      setDtTextDomain('<?php echo $this->basePath() . '/js/locale'; ?>');
      setDtLocale('<?php echo $_SESSION['bareos']['locale']; ?>');

      attachJobTable();

      $('#jobtable').on('load-error.bs.table', function(status, res) {
         $("#modal-001").modal();
      });

      $('#rangeslider').on('slideStop', getSliderValue);

   });

   // Remember rangeslider value
   $(document).on('input', '#rangeslider', function() {
      displayRange = $(this).val();
   });

</script>

<?php endif; ?>
