{% extends "base/base_layout.html" %}
{% load static %}
 {% block sidebar_option %}
      sidebar-collapse
{% endblock %}
{% block extra_css %}
<!-- DataTables -->
<link rel="stylesheet" href="{% static "adminlte/plugins/datatables-bs4/dataTables.bootstrap4.min.css" %}">
{% endblock %}
{% block content %}
<div class="content-wrapper">
  <div class="content-header">
  </div>
   <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
            <div class="card">
              <div class="card-body">
                <h3 class="page-header"><strong>iOS API Monitor </strong>- {{ bundle_id }}</h3>
                <div id="messages"></br>Data refreshed in every 10 seconds.</div>
                <div align="right">Data Snip:  <input type="text" id="snip" value="5000" oninput="change_snip(this.value)"></div><br />
                <div class="table-responsive">
                <table id="autotbl" class="table table-bordered table-hover table-striped" style="width:100%">
                        <thead>
                            <tr>
                                <th>API</th>
                                <th>DATA</th>
                            </tr>
                        </thead>
                        <tfoot>
                            <tr>
                                <th>API</th>
                                <th>DATA</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>

          </div>
        </div>
       </div>
     </div>
    </div>
</div>
{% endblock %}
{% block extra_scripts %}
<!-- DataTables -->
<script src="{% static "adminlte/plugins/datatables/jquery.dataTables.min.js" %} "></script>
<script src="{% static "adminlte/plugins/datatables-bs4/dataTables.bootstrap4.min.js" %}"></script>
<script type="text/javascript">
var snip = document.getElementById('snip').value;
var tbl;

function change_snip(val){
    snip = parseInt(val);
    tbl.ajax.reload();
}

 // HTML escape function
 function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

// Function to flatten and format data in one pass
function formatFlattenedData(data) {
    if (!data || typeof data !== 'object') {
        return escapeHtml(JSON.stringify(data));
    }
    
    const formatted = [];
    
    function flattenAndFormat(obj) {
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                const value = obj[key];
                
                if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
                    // Recursively process nested objects
                    flattenAndFormat(value);
                } else if (Array.isArray(value)) {
                    // Handle arrays
                    if (value.length > 0 && typeof value[0] === 'object') {
                        // Array of objects - process each object
                        value.forEach(item => {
                            if (typeof item === 'object' && item !== null) {
                                flattenAndFormat(item);
                            } else {
                                formatted.push(`<strong>${escapeHtml(key)}</strong>: ${escapeHtml(String(item))}`);
                            }
                        });
                    } else {
                        // Array of primitives
                        formatted.push(`<strong>${escapeHtml(key)}</strong>: ${escapeHtml(JSON.stringify(value))}`);
                    }
                } else {
                    // Handle primitive values
                    formatted.push(`<strong>${escapeHtml(key)}</strong>: ${escapeHtml(String(value))}`);
                }
            }
        }
    }
    
    flattenAndFormat(data);
    return formatted.join('<br>');
}

$(document).ready( function () {
        $.fn.dataTable.ext.errMode = 'none';
        tbl = $('#autotbl').DataTable( {
        ajax: '{% url "ios_api_monitor" %}?checksum={{ checksum }}&stream=1',
        deferRender:    true,
        scroller:       true,
        scrollX:        true,
        searching:      true,
        paging:         false,
        info:           true,
        processing:     true,
        serverSide:     false,
        columns: [
            { data: "api" },
            { data: "data" },
        ],
        columnDefs: [ {
            targets: [1],
            render: function (data, type, row) {
                    const formattedData = formatFlattenedData(data);
                    return formattedData.length > snip ?
                        formattedData.slice(0, snip) + "..." :
                        formattedData;
                }
               
           }
        ]
    });
    setInterval( function () {
        tbl.ajax.reload(null, false); // false = don't reset paging
    }, 10000 );
});

</script>
{% endblock %}