{% extends 'layouts/base.html' %}

{% block title %} System view - {{res}} {% endblock title %}

<!-- Specific CSS goes HERE -->
{% block stylesheets %}
<link rel="stylesheet" href="/static/assets/css/style.css">



{% endblock stylesheets %}

{% block content %}

<!-- Header -->
<div class="header bg-primary pb-6">
  <div class="container-fluid">
    <div class="header-body">
      <div class="row align-items-center py-4">
        <div class="col-lg-6 col-7">

          <nav aria-label="breadcrumb" class="d-none d-md-inline-block ml-md-4">
            <a href="{{url_for('admin.dashboard')}}">
              <ol class="breadcrumb breadcrumb-links breadcrumb-dark">
                <li class="breadcrumb-item"><i class="fas fa-home"></i></li>
              </ol>
            </a>
          </nav>

          <nav aria-label="breadcrumb" class="d-none d-md-inline-block ml-md-4">
            <a href="/dashboard/{{res}}">
              <ol class="breadcrumb breadcrumb-links breadcrumb-dark">
                <li class="breadcrumb-item">Application View</li>
              </ol>
            </a>
          </nav>

          <nav aria-label="breadcrumb" class="d-none d-md-inline-block ml-md-4">
            <ol class="breadcrumb breadcrumb-links breadcrumb-dark"
              style="background-color: #337ab7;color: white; font-family: 'Arial', sans-serif" ;>
              <li class="breadcrumb-item">System View</li>
            </ol>
          </nav>
        </div>

        <div class="col-lg-2 col-7 text-right">
          <nav aria-label="breadcrumb" class="d-none d-md-inline-block">
              <h3>Session time: <span id="session-time"></span></h3>
          </nav>
      </div>


        <div class="col-lg-4 col-5 text-right">
          <u><a href="/download/{{res}}" style="text-align: right; font-weight: bold;">Backup Overview Report</a></u>
          <!-- <a href="#" class="btn btn-sm btn-neutral">Filters</a> -->
        </div>
      </div>
      <!-- Card stats -->
    </div>
  </div>
</div>
<!-- Page content -->
<div class="container-fluid mt--6">
  <div class="row">
    <div class="col">
      <div class="card">
        <!-- Card header -->
        <div class="card-header border-0">
          <h3 class="mb-0">Details</h3>
        </div>
        <!-- Light table -->
        <div class="table-responsive">
          <table class="table align-items-center table-flush">
            <thead class="thead-light">
              <tr>
                <th scope="col" class="sort" data-sort="name">FQDN</th>
                <th scope="col" class="sort" data-sort="status">Machine Type</th>
                <th scope="col" class="sort" data-sort="status">Version</th>
                <th scope="col" class="sort" data-sort="name">Last Updated On</th>
                <th scope="col" class="sort" data-sort="name">Uptime Status</th>
                <th scope="col" class="sort" data-sort="name">status</th>
                <th scope="col" class="sort" data-sort="status">Last Mongo Backup On</th>
                <th scope="col" class="sort" data-sort="status">Nightly Restart</th>
                <th scope="col" class="sort" data-sort="budget">Ram</th>
                <th scope="col" class="sort" data-sort="status">Free Ram</th>
                <th scope="col" class="sort" data-sort="status">Available for Applications</th>
                <th scope="col" class="sort" data-sort="status">Swap</th>
                <th scope="col" class="sort" data-sort="status">Cores</th>
                <th scope="col" class="sort" data-sort="status">/ Total</th>
		            <th scope="col" class="sort" data-sort="status">/ Used</th>
                <th scope="col" class="sort" data-sort="status">/ Available</th>
                <th scope="col" class="sort" data-sort="status">/parablu</th>
                <th scope="col" class="sort" data-sort="status">/parablu used</th>
                <th scope="col" class="sort" data-sort="status">/parablu Available</th>
                <th scope="col" class="sort" data-sort="status">View History</th>
              </tr>
            </thead>
            <tbody class="list">
              {% for customer in datas %}
              <tr>
                <th scope="row">
                  <div class="media align-items-center">
                    {% if customer['System Name'] == "0" %}
                      
                    {% else %}
                    <a data-id="{{customer['System Name']}}" data-type="{{res}}" class="serverUptime"
                      style="cursor: pointer;">
                      <u><span class="name mb-0 text-sm">{{customer['System Name']}}</span></u>
                    </a>
                    {% endif %}

                  </div>
                </th>
                <td class="budget">
                  {% if customer['System Name'] == "0" %}

                  {% elif customer['MachineTypeValue'] == 0 %}
                  All in One
                  {% elif customer['MachineTypeValue'] == 1 %}
                  Only Paracloud
                  {% elif customer['MachineTypeValue'] == 2 %}
                  Only Blukrypt
                  {% elif customer['MachineTypeValue'] == 3 %}
                  PRIMARY MONGO
                  {% elif customer['MachineTypeValue'] == 4 %}
                  SECONDARY MONGO
                  {% elif customer['MachineTypeValue'] == 5 %}
                  MONGODB BACKUP
                  {% elif customer['MachineTypeValue'] == 8 %}
                  Paracloud & Blukrypt
                  {% elif customer['MachineTypeValue'] == 9 %}
                  Paracloud & Mongo
                  {% endif %}
                </td>
                
                {% if customer['System Name'] == "0" %}
                <td class="budget">
             
                </td>
                {% else %}
                <td class="budget">
                  {{customer['MachineVersion']}}
                </td>
                {% endif %}
                {% if customer['System Name'] == "0" %}
                <td class="budget">
           
                </td>
                {% else %}
                <td class="budget">
                  {{customer['Date & Time '] }}
                </td>
                {% endif %}

                <td id="{{ loop.index }}">Waiting for response...</td>
                <td id="status-{{customer['System Name']}}"></td>


                {% if customer['System Name'] == "0" %}
                <td class="budget">
              
                </td>
                {% else %}
                <td class="budget" style="color: {{customer['lastMongoUpdateColor']}};">
                  {% if customer['lastMongoUpdate'] != "0" %}
                  {{customer['lastMongoUpdate']}}
                  {% else %}
                  Not yet updated
                  {% endif %}
                </td>
                {% endif %}
      
                {% if customer['System Name'] == "0" %}
                <td class="budget">
                  
                </td>
                {% else %}
                <td class="budget" style="color: {{customer['nightlyRestartColor']}};">
                  {% if customer['lastNightlyRestart'] != "0" %}
                  {{customer['lastNightlyRestart'] }}
                  {% else %}
                  Not yet updated
                  {% endif %}
                </td>
                {% endif %}


                {% if customer['System Name'] == "0" %}
                <td class="budget">
     
                </td>
                {% else %}
                <td>
                  <span class="badge badge-dot mr-4">
                    <span class="status">{{customer['Total Physical Memory'] | bytes_to_gb}}</span>
                    <!-- <span class="status">8</span> -->
                  </span>
                </td>
                {% endif %}

                {% if customer['System Name'] == "0" %}
                <td class="budget">
   
                </td>
                {% else %}
                <td class="budget">
                  {{customer['Free Physical Memory'] |bytes_to_gb}}
                  <!-- <span class="badge badge-info">80%</span> -->
                  <span class="mr-2">({{customer['Freepercentage'] |round(2)}}%)</span>
                  <div>
                    <div class="progress">
                      <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100" aria-valuemin="0"
                        aria-valuemax="100" style="width: {{customer['Freepercentage'] |round(2)}}%;"></div>
                    </div>
                  </div>
                </td>
                {% endif %}
                
                {% if customer['System Name'] == "0" %}
                <td class="budget">
           
                </td>
                {% else %}
                <td class="budget">
                  {{customer['Available'] |bytes_to_gb}}
                  <span class="mr-2">({{customer['finalAvailablePercentage'] |round(2)}}%)</span>
                  <div>
                    <div class="progress">
                      <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100" aria-valuemin="0"
                        aria-valuemax="100" style="width: {{customer['finalAvailablePercentage'] |round(2)}}%;"></div>
                    </div>
                  </div>
                </td>
                {% endif %}
                
                {% if customer['System Name'] == "0" %}
                <td class="budget">
            
                </td>
                {% else %}
                <td class="budget" style="color: {{customer['swapSpaceColor']}};">
                  {{customer['Swap Memory / Disabled'] | bytes_to_gb}}
                </td>
                {% endif %}
                
                {% if customer['System Name'] == "0" %}
                <td class="budget">
    
                </td>
                {% else %}
                <td class="budget">
                  {{customer['Processor'] }}
                </td>
                {% endif %}
                

                {% if customer['System Name'] == "0" %}
                <td class="budget">
     
                </td>
                {% else %}
                <td class="budget">
                  {{customer['Total Space'] |lstrip_zero}}
                </td>
                {% endif %}
                
		{% if customer['System Name'] == "0" %}
                <td class="budget">

                </td>
                {% else %}
                <td class="budget">
                  {{customer['Usable Space'] |lstrip_zero}}
                </td>
                {% endif %}



                {% if customer['System Name'] == "0" %}
                <td class="budget">
               
                </td>
                {% else %}
                <td class="budget">
                  {{customer['Free Space'] |lstrip_zero }}
                </td>
                {% endif %}


                {% if customer['System Name'] == "0" %}
                <td class="budget">
                  
                </td>
                {% else %}
                <td class="budget">
                  {% if customer['parabluSizeSystem'] == "" %}
                  --------
                  {% else %}
                  {{customer['parabluSizeSystem'] | add_space }}
                  {% endif %}
                </td>
                {% endif %}

                {% if customer['System Name'] == "0" %}
                <td class="budget">
                  
                </td>
                {% else %}
                
                <td class="budget" style="color:{{customer['percentageUserdBytesColors']}} ">
                  {{customer['parabluUsedSystem'] |add_space}}
                  <span class="mr-2">({{customer['percentageUserdBytes'] |round(2)}}%)</span>
                  <div>
                    <div class="progress">
                      <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100" aria-valuemin="0"
                        aria-valuemax="100" style="width: {{customer['percentageUserdBytes'] |round(2)}}%;"></div>
                    </div>
                  </div>
                </td>
                {% endif %}


                {% if customer['System Name'] == "0" %}
                <td class="budget">
                  
                </td>
                {% else %}
                <td class="budget" style="color: {{customer['percentageAvailableColor']}};">
                  {% if customer['parabluDiskAvailableSize'] == "0" %}
                    N/A
                  {% else %}
                  {{customer['parabluDiskAvailableSize']}}
                  <span class="mr-2">({{customer['percentageAvailable'] |round(2)}}%)</span>
                  <div>
                    <div class="progress">
                      <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100" aria-valuemin="0"
                        aria-valuemax="100" style="width: {{customer['percentageAvailable'] |round(2)}}%;"></div>
                    </div>
                  </div>
                  {% endif %}
                </td>
                {% endif %}

                {% if customer['System Name'] == "0" %}

                {% else %}
                <td class="budget">
                  <a data-id="{{customer['System Name']}}" data-type="{{res}}" class="serverHistory"
                      style="cursor: pointer;">
                      <u><span class="name mb-0 text-sm">Click Here</span></u>
                    </a>
                </td>
                {% endif %}
              </tr>
              {% endfor %}              
            </tbody>
          </table>
        </div>
        <!-- Card footer -->
        <div class="card-footer py-4">
          <nav aria-label="...">

          </nav>
        </div>
      </div>
    </div>
  </div>




  {% include "includes/footer.html" %}

</div>


<div class="modal fade" id="chooseModalUptime" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">{{cloudName}}</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body anand123">
        ...
      </div>
      <div class="modal-footer">

      </div>
    </div>
  </div>
</div>


<div class="modal fade" id="clickMoreinfo" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">More Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


<div class="modal fade" id="empModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>

    </div>
  </div>
</div>


<div class="modal fade" id="clickApache" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Apache Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


<div class="modal fade" id="serverHistiry" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <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>
      </div>
      <div class="modal-body serverHist">
        ...
      </div>
      <div class="modal-footer">

      </div>
    </div>
  </div>
</div>

{% endblock content %}

{% block javascripts %}


<script type='text/javascript'>
  $(document).ready(function () {
    $('.serverUptime').click(function () {
      var userid = $(this).data('id');
      var systemType = $(this).data('type');
      $.ajax({
        url: '/uptime',
        type: 'post',
        data: { userid: userid, res: systemType },
        success: function (data) {
          $('.anand123').html(data);
          $('.anand123').append(data.htmlresponse);
          $('#chooseModalUptime').modal('show');
        }
      });
    });
  });
</script>

<script type='text/javascript'>
  $(document).ready(function () {
    $('.serverHistory').click(function () {
      var userid = $(this).data('id');
      var systemType = $(this).data('type');
      console.log("The userid is "+userid)
      console.log("The systemType is "+systemType)
      $.ajax({
        url: '/serverHistory',
        type: 'post',
        data: { userid: userid, res: systemType },
        success: function (data) {
          $('.serverHist').html(data);
          $('.serverHist').append(data.htmlresponse);
          $('#serverHistiry').modal('show');
        }
      });
    });
  });
</script>


<script>
  $('#chooseModalUptime').on('hidden.bs.modal', function () {

    location.reload();

  });
</script>


<script>
  const rows = document.querySelectorAll('tbody tr');

  rows.forEach(row => {
    const timeCell = row.cells[3];
    const time = timeCell.textContent.trim();

    if (time !== '') {
      const dateTime = new Date(time);
      const now = new Date();
      const diffInMs = now - dateTime;
      const diffInHrs = Math.floor(diffInMs / (1000 * 60 * 60));

      if (diffInHrs >= 6){
        row.cells[5].textContent = 'Down since ' + diffInHrs + ' hours';
        row.cells[5].style.color = 'red';
      } else {
        row.cells[5].textContent = 'Running Successfully';
        row.cells[5].style.color = 'green';
      }
    }
  });
</script>


<script type='text/javascript'>
  $(document).ready(function () {
    $('.user').click(function () {
      var userid = $(this).data('id');
      $.ajax({
        url: '/color',
        type: 'post',
        data: { userid: userid },
        success: function (data) {
          $('.modal-body').html(data);
          $('.modal-body').append(data.htmlresponse);
          $('#empModal').modal('show');
        }
      });
    });
  });
</script>


<script type='text/javascript'>
  $(document).ready(function () {
    $('.apachedetails').click(function () {
      var userid = $(this).data('id');
      $.ajax({
        url: '/apacheDetails',
        type: 'post',
        data: { userid: userid },
        success: function (data) {
          $('.modal-body').html(data);
          $('.modal-body').append(data.htmlresponse);
          $('#clickApache').modal('show');
        }
      });
    });
  });
</script>


<script type='text/javascript'>
  $(document).ready(function () {
    $('.clickMore').click(function () {
      var userid = $(this).data('id');
      $.ajax({
        url: '/clickMore',
        type: 'post',
        data: { userid: userid },
        success: function (data) {
          $('.modal-body').html(data);
          $('.modal-body').append(data.htmlresponse);
          $('#clickMoreinfo').modal('show');
        }
      });
    });
  });
</script>

<script>
  function updateSessionTime() {
      var start = new Date('{{ session.logged_in_at }}' * 1000);  // Convert Unix timestamp to JavaScript date
      var now = new Date();
      var elapsed = now - start;
      var hours = Math.floor(elapsed / (1000 * 60 * 60));
      var minutes = Math.floor((elapsed / (1000 * 60)) % 60);
      var seconds = Math.floor((elapsed / 1000) % 60);
      var sessionTime = hours + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');
      document.getElementById('session-time').textContent = sessionTime;
  }
  setInterval(updateSessionTime, 1000);  // Update session time every second
</script>


<script>
  function pingUrl() {
      const url = document.getElementById('urlInput').value;
      let finalUrl = "https://"+url;
      fetch(`/ping?url=${encodeURIComponent(finalUrl)}`)
          .then(response => response.text())
          .then(text => {
              const statusCell = document.getElementById('status');
              statusCell.innerText = text;
          });
  }

  function pingAllUrls() {
      const rows = document.getElementsByTagName('tr');
      for (let i = 1; i < rows.length; i++) {
          const urlCell = rows[i].cells[0];
          const statusCell = rows[i].cells[4];
          const url = urlCell.innerText;
          const machineType = rows[i].cells[1];
          console.log("Machine type is ");
             console.log(machineType);
          let finalUrl = "https://"+url;
          console.log("the final url is");
              console.log(finalUrl)
          if(machineType.innerText === "Only Blukrypt"){
            console.log("The Machine type is Blukrypt");

            finalUrl = finalUrl + "/BluKryptBuilder/healthcheck/";
            console.log(finalUrl)
          }
          fetch(`/ping?url=${encodeURIComponent(finalUrl)}`)
              .then(response => response.text())
              .then(text => {
                  statusCell.innerText = text;
                  if (text.toLowerCase() === "up") {
                    statusCell.style.color = "green";
                  } else {
                      statusCell.style.color = "red";
                  }
              });
      }
  }

  setTimeout(pingAllUrls, 500); // Wait for 5 seconds and then call pingAllUrls
</script>

{% endblock javascripts %}
