<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ page_title }}</title>
    {% set bloom_mod = 'index' %}
    <link rel="stylesheet" type="text/css" href="{{ style.skin_css }}">
    <link rel="stylesheet" type="text/css" href="/static/legacy/style.css">
    <script src="/static/legacy/action_buttons.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/9.5.6/jsoneditor.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/9.5.6/jsoneditor.min.js"></script>
    <style>
        .floating-button { /* styles */ }
        .form-section { /* styles */ }
        .form-group { /* styles */ }
        .glow { /* styles */ }
        th { /* styles */ }
        .option-buttons {
            display: flex;
            flex-wrap: wrap;
            margin-left: 10px;
        }
        .option-button {
            margin: 5px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            cursor: pointer;
        }
        .option-button.selected {
            background-color: #007BFF;
            color: white;
            border-color: #007BFF;
        }
        .nested-json {
            margin-left: 20px;
        }
        .form-container input {
            margin-bottom: 5px;
        }
        .highlight {
            background-color: magenta;
        }
    </style>
    <link rel="stylesheet" type="text/css" href="/static/legacy/skins/json_editor.css">

</head>
<body id="content2">
    {% include 'legacy/bloom_header.html' %}

    <small><a href=dindex2?globalStartNodeEUID={{ object.euid }}>( graph )</a></small>

    <h1>Object Details : {{ object.euid }}</h1>

    <table width="100%">
        <tr width="100%">
            <td width="50%"></td>
            <td width="50%" align="right"></td>
        </tr>
    </table>

    <table>
        <tr>
            <td>S3 URI</td>
            <td>{{  object.json_addl['properties']['current_s3_uri'] }} -- <small><a href="https://us-east-1.console.aws.amazon.com/s3/buckets/{{ object.json_addl.properties.current_s3_bucket_name }}?region=us-east-1&bucketType=general&prefix={{ object.json_addl.properties.current_s3_key }}" target=rlink>redirect aws linkout</a></small></td>
        </tr>
        <tr>
            <td>EUID</td>
            <td><a class="reference-link" href="euid_details?euid={{ object.euid }}">{{ object.euid }}</a>
            
                {%if  object.json_addl.properties.ref_type and object.json_addl['properties']['ref_type']  == "presigned_url" %}
                -- ( <a href="file_set_urls?fs_euid={{ object.euid }}">presigned urls</a> )
		     {% else %}
        	
		    {% endif %}


            </td>
        </tr>

        <tr>
            <td>Given Name</td>
            <td>{{ object.json_addl['properties']['name'] }}</td>
        </tr>
       
      
        <tr>
            <td>Polymorphic Discriminator</td>
            <td>{{ object.polymorphic_discriminator }}</td>
        </tr>
        <tr>
            <td>Category</td>
            <td>{{ object.category }}</td>
        </tr>
        <tr>
            <td>Type</td>
            <td>{{ object.type }}</td>
        </tr>
        <tr>
            <td>Subtype</td>
            <td>{{ object.subtype }}</td>
        </tr>
        <tr>
            <td>Version</td>
            <td>{{ object.version }}</td>
        </tr>
        <tr>
            <td>Status</td>
            <td>{{ object.bstatus }}</td>
        </tr>
        <tr>
            <td>Created Date</td>
            <td>{{ object.created_dt }}</td>
        </tr>
        <tr>
            <td>Is Deleted?</td>
            <td>{{ object.is_deleted }}</td>
        </tr>
        <tr>
            <td>Template EUID</td>
            <td>
                {% if object.parent_template_euid %}
                    <a href="euid_details?euid={{ object.parent_template_euid }}">{{ object.parent_template_euid }}</a>
                {% else %}
                    This is a TEMPLATE Object: <a href="/admin_template?euid={{ object.euid }}">admin edit</a>
                {% endif %}
            </td>
        </tr>
        <tr>
            <td>UUID</td>
            <td><a class="reference-link" href="uuid_details?uuid={{ object.uuid }}">{{ object.uuid }}</a></td>
        </tr>
    </table>

    <hr>

    <div class="collapsible-buttons">
        <button type="button" class="collapsiblex" data-target="relationshipsContent">Relationships</button>
        {% if subjects_for_object %}
        <button type="button" class="collapsiblex" data-target="subjectsContent">Subjects ({{ subjects_for_object|length }})</button>
        {% endif %}
        <button style="display:none;" type="button" class="collapsiblex" data-target="dynamicFieldsContent">Dynamic Fields</button>
        <button type="button" class="collapsiblex" data-target="actionGroupsContent">Action Groups</button>
        <button type="button" class="collapsiblex" data-target="auditLogContent">Audit Log</button>
        <button type="button" class="collapsiblex" data-target="fullEditContent">Edit Obj Properties (admin)</button>
        {% if object.parent_template_euid %}

        {% else %}
            <button type="button" class="collapsiblex" data-target="fullEditContentTemplate">Edit Template Form Properties (super admin)</button>
        {% endif %}
    </div>

    <hr>

    <div id="relationshipsContent" class="content" style="display:none;">
        <h2>Relationships</h2>
        <h3>Child Of Lineages</h3>
        <table class="searchable">
            <tr>
                <th>Status</th>
                <th>Parent</th>

                <th>Parent Type</th>
                <th>Parent Sub Type</th>
                <th>Parent Version</th>
                <th>Parent Instance EUID</th>

                <th>Child</th>
                <th>Child Type</th>
                <th>Child Sub Type</th>
                <th>Child Version</th>
                <th>Child Instance EUID</th>


                <th>Relationship Type</th>
                <th>Lineage EUID</th>


            </tr>
            {% for lineage in oobj.child_of_lineages %}
                <tr{% if lineage.is_deleted %} style="background-color: #ffcccc; text-decoration: line-through;"{% endif %}>
                    <td>
                        {% if lineage.is_deleted %}
                            <span style="color: red; font-weight: bold;" title="Soft Deleted">🗑️ DELETED</span>
                        {% else %}
                            <span style="color: green;" title="Active">✓ Active</span>
                        {% endif %}
                    </td>
                    <td>{{ lineage.parent_instance.category }}</td>

                    <td>{{ lineage.parent_instance.type }}</td>
                    <td>{{ lineage.parent_instance.subtype }}</td>
                    <td>{{ lineage.parent_instance.version }}</td>
                    <td><a href="euid_details?euid={{ lineage.parent_instance.euid }}">{{ lineage.parent_instance.euid }}</a></td>

                    <td>{{ lineage.child_instance.category }}</td>
                    <td>{{ lineage.child_instance.type }}</td>
                    <td>{{ lineage.child_instance.subtype }}</td>
                    <td>{{ lineage.child_instance.version }}</td>
                    <td><a href="euid_details?euid={{ lineage.child_instance.euid }}">{{ lineage.child_instance.euid }}</a></td>


                    <td>{{ lineage.relationship_type }}</td>
                    <td><a href="euid_details?euid={{ lineage.euid }}">{{ lineage.euid }}</a></td>

                </tr>
            {% endfor %}
        </table>
        <h3>Parent Of Lineages</h3>
        <table class="searchable">
            <tr>
                <th>Status</th>
                <th>Parent</th>
                <th>Parent Type</th>
                <th>Parent Sub Type</th>
                <th>Parent Version</th>
                <th>Parent Instance EUID</th>

                <th>Child</th>
                <th>Child Type</th>
                <th>Child Sub Type</th>
                <th>Child Version</th>
                <th>Child Instance EUID</th>

                <th>Relationship Type</th>
                <th>Lineage EUID</th>

            </tr>
            {% for lineage in oobj.parent_of_lineages %}
                <tr{% if lineage.is_deleted %} style="background-color: #ffcccc; text-decoration: line-through;"{% endif %}>
                    <td>
                        {% if lineage.is_deleted %}
                            <span style="color: red; font-weight: bold;" title="Soft Deleted">🗑️ DELETED</span>
                        {% else %}
                            <span style="color: green;" title="Active">✓ Active</span>
                        {% endif %}
                    </td>
                    <td>{{ lineage.parent_instance.category }}</td>

                    <td>{{ lineage.parent_instance.type }}</td>
                    <td>{{ lineage.parent_instance.subtype }}</td>
                    <td>{{ lineage.parent_instance.version }}</td>
                    <td><a href="euid_details?euid={{ lineage.parent_instance.euid }}">{{ lineage.parent_instance.euid }}</a></td>

                    <td>{{ lineage.child_instance.category }}</td>
                    <td>{{ lineage.child_instance.type }}</td>
                    <td>{{ lineage.child_instance.subtype }}</td>
                    <td>{{ lineage.child_instance.version }}</td>
                    <td><a href="euid_details?euid={{ lineage.child_instance.euid }}">{{ lineage.child_instance.euid }}</a></td>

                    <td>{{ lineage.relationship_type }}</td>
                    <td><a href="euid_details?euid={{ lineage.euid }}">{{ lineage.euid }}</a></td>
                </tr>
            {% endfor %}
        </table>
    </div>

    {% if subjects_for_object %}
    <div id="subjectsContent" class="content" style="display:none;">
        <h2>Subjects (Decision Scopes)</h2>
        <p><em>This object is part of the following subjects:</em></p>
        <table class="searchable">
            <tr>
                <th>Subject EUID</th>
                <th>Kind</th>
                <th>Role</th>
                <th>Status</th>
                <th>Subject Key</th>
                <th>Name</th>
            </tr>
            {% for subject in subjects_for_object %}
            <tr>
                <td><a href="euid_details?euid={{ subject.euid }}">{{ subject.euid }}</a></td>
                <td>{{ subject.kind }}</td>
                <td>
                    {% if subject.role == 'anchor' %}
                        <span style="color: #007BFF; font-weight: bold;">⚓ Anchor</span>
                    {% elif subject.role == 'member' %}
                        <span style="color: #28a745;">📎 Member</span>
                    {% else %}
                        {{ subject.role }}
                    {% endif %}
                </td>
                <td>{{ subject.status }}</td>
                <td><code>{{ subject.subject_key }}</code></td>
                <td>{{ subject.name }}</td>
            </tr>
            {% endfor %}
        </table>
    </div>
    {% endif %}

    <div id="dynamicFieldsContent" class="content" style="display:none;">
        <div class="dynamic-fields">
            <h2>Dynamic Fields</h2>
            <table>
                {% for key, value in object|dictsort %}
                    {% if key not in static_fields and not key.endswith('_uuid') %}
                        <tr>
                            <td>{{ key|capitalize }}</td>
                            <td>{{ value }}</td>
                        </tr>
                    {% elif key.endswith('_uuid') %}
                        <tr>
                            <td>{{ key|capitalize }}</td>
                            <td><a class="reference-link" href="uuid_details?uuid={{ value }}">{{ value }}</a></td>
                        </tr>
                    {% endif %}
                {% endfor %}
            </table>
        </div>
    </div>

    <div id="actionGroupsContent" class="content" style="display:none;">
        {% if object.json_addl and 'action_groups' in object.json_addl %}
            <div class="action-group-group">
                {% for group_key, group_value in object.json_addl['action_groups'].items() %}
                    <div class="action-group">
                        {{ group_value.group_name }}
                        {% for action_key, action_value in group_value.actions.items() %}
                            <button class="action_button"
                                    onclick="showCapturedDataForm(this, {{ action_value }}, '{{ object.euid }}', '{{ action_key }}', '{{ group_key }}')"
                                    {% if action_value.action_enabled == "0" %}disabled style="color: gray;"{% endif %}>
                                {{ action_value.action_name }}
                            </button>
                        {% endfor %}
                    </div>
                {% endfor %}
            </div>
        {% endif %}
    </div>

    <div id="auditLogContent" class="content" style="display:none;">
        <h2>Audit Log</h2>
        {% if audit_logs %}
            <table id="auditLogTable">
                <thead>
                    <tr>
                        <th onclick="sortTable(0)">Column Name</th>
                        <th onclick="sortTable(1)">Old Value</th>
                        <th onclick="sortTable(2)">New Value</th>
                        <th onclick="sortTable(3)">Changed By</th>
                        <th onclick="sortTable(4)">Changed At</th>
                        <th onclick="sortTable(5)">Operation Type</th>
                    </tr>
                </thead>
                <tbody>
                    {% for log in audit_logs %}
                        <tr>
                            <td>{{ log.column_name }}</td>
                            {% if log.column_name == 'json_addl' %}
                                <td>
                                    <button id="jsonToggleButton-{{ loop.index }}" onclick="toggleJSONDisplay({{ loop.index }})">Show JSON</button>
                                    <div id="jsonOldContent-{{ loop.index }}" style="display:none;">{{ log.old_value }}</div>
                                </td>
                                <td><div id="jsonNewContent-{{ loop.index }}" style="display:none;">{{ log.new_value }}</div></td>
                            {% else %}
                                <td>{{ log.old_value }}</td>
                                <td>{{ log.new_value }}</td>
                            {% endif %}
                            <td>{{ log.changed_by }}</td>
                            <td>{{ log.changed_at }}</td>
                            <td>{{ log.operation_type }}</td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        {% else %}
            <p>No audit log entries found.</p>
        {% endif %}
    </div>

    <div id="jsonAddlContent" class="content" style="display:none;">
        <h2>Edit json_addl</h2>
        <form id="prop-{{ object.euid }}" method="post" action="/update_obj_json_addl_properties" class="form-container">
            <input type="hidden" name="obj_euid" value="{{ object.euid }}">
            {% for key, value in object.json_addl['properties'].items() %}
                <div>
                    <label for="{{ object.euid }}">{{ key }}:</label>
                    {% if value is string %}
                        <input type="text" id="{{ object.euid }}" name="{{ key }}" value="{{ value }}">
                    {% elif value is iterable %}
                        <div id="list-{{ object.euid }}-{{ key }}">
                            {% for item in value %}
                                <input id="{{ object.euid }}" type="text" name="{{ key }}[]" value="{{ item }}">
                            {% endfor %}
                        </div>
                        <button class="form-button" type="button" onclick="addListItem('{{ object.euid }}', '{{ key }}')">Add</button>
                        <button class="form-button" type="button" onclick="removeListItem('{{ object.euid }}', '{{ key }}')">Remove</button>
                    {% else %}
                        <input type="text" id="{{ object.euid }}" name="{{ key }}" value="{{ value }}">
                    {% endif %}
                </div>
            {% endfor %}
            <div>
                <input type="submit" value="Save Changes" class="form-button">
            </div>
        </form>
    </div>

    <div id="fullEditContent" class="content" style="display:none;">
        <h2>Edit Object 'properties'</h2>
        <form id="full-edit-form">
            <div id="json-editor"></div>
            <input type="hidden" id="object_json_key" name="object_json_key" value="properties">
            <button type="button" onclick="saveFullEdit()">Save</button>
        </form>
    </div>

    <div id="fullEditContentTemplate" class="content" style="display:none;">
        <h2>Edit Template Form Controlled Dict</h2>
        <form id="full-edit-form-template">
            <div id="json-editor-template"></div>
            <input type="hidden" id="object_json_key_template" name="object_json_key_template" value="controlled_properties">
            <button type="button" onclick="saveFullEditTemplate()">Save</button>
        </form>
    </div>

    <script>
        var coll = document.getElementsByClassName("collapsiblex");
        var i;

        for (i = 0; i < coll.length; i++) {
            coll[i].addEventListener("click", function() {
                this.classList.toggle("active");
                var content = document.getElementById(this.getAttribute('data-target'));
                if (content.style.display === "block") {
                    content.style.display = "none";
                } else {
                    content.style.display = "block";
                }
            });
        }

        function sortTable(columnIndex) {
            var table, rows, switching, i, x, y, shouldSwitch;
            table = document.getElementById("auditLogTable");
            switching = true;

            if (columnIndex === currentSortColumn) {
                sortAscending = !sortAscending; // Toggle the sorting direction
            } else {
                currentSortColumn = columnIndex;
                sortAscending = true; // Default to ascending sort for a new column
            }

            while (switching) {
                switching = false;
                rows = table.rows;

                for (i = 1; i < (rows.length - 1); i++) {
                    shouldSwitch = false;
                    x = rows[i].getElementsByTagName("TD")[columnIndex];
                    y = rows[i + 1].getElementsByTagName("TD")[columnIndex];

                    if (sortAscending) {
                        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                            shouldSwitch = true;
                            break;
                        }
                    } else {
                        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                            shouldSwitch = true;
                            break;
                        }
                    }
                }

                if (shouldSwitch) {
                    rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                    switching = true;
                }
            }
        }

        function addListItem(euid, key) {
            var listContainer = document.getElementById('list-' + euid + '-' + key);
            var newItem = document.createElement('input');
            newItem.setAttribute('type', 'text');
            newItem.setAttribute('name', key + '[]');
            listContainer.appendChild(newItem);
        }

        function removeListItem(euid, key) {
            var listContainer = document.getElementById('list-' + euid + '-' + key);
            if (listContainer.children.length > 0) {
                listContainer.removeChild(listContainer.lastChild);
            }
        }

        function saveFullEdit() {
            var editorContent = JSON.stringify(editor.get(), null, 4);
            try {
                var parsedJson = JSON.parse(editorContent);
                $.ajax({
                    url: '/save_json_addl_key',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ 
                        euid: '{{ object.euid }}', 
                        json_data: parsedJson,
                        json_addl_key: document.getElementById('object_json_key').value
                    }),
                    success: function(response) {
                        window.location.href = "euid_details?euid={{ object.euid }}";
                    },
                    error: function(error) {
                        alert('Error saving JSON: ' + error.responseText);
                    }
                });
            } catch (e) {
                alert('Invalid JSON: ' + e.message);
            }
        }

        function saveFullEditTemplate() {
            var editorContentTemplate = JSON.stringify(editorTemplate.get(), null, 4);
            try {
                var parsedJsonTemplate = JSON.parse(editorContentTemplate);
                $.ajax({
                    url: '/save_json_addl_key',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ 
                        euid: '{{ object.euid }}', 
                        json_data: parsedJsonTemplate,
                        json_addl_key: document.getElementById('object_json_key_template').value
                    }),
                    success: function(response) {
                        window.location.href = "euid_details?euid={{ object.euid }}";
                    },
                    error: function(error) {
                        alert('Error saving JSON: ' + error.responseText);
                    }
                });
            } catch (e) {
                alert('Invalid JSON: ' + e.message);
            }
        }

        var editor, editorTemplate;
        $(document).ready(function() {
            var container = document.getElementById('json-editor');
            var options = {};
            editor = new JSONEditor(container, options);
            editor.set({{ jaddl_prop|tojson }});

            var containerTemplate = document.getElementById('json-editor-template');
            editorTemplate = new JSONEditor(containerTemplate, options);
            editorTemplate.set({{ jaddl_controlled_prop|tojson }});
        });
    </script>

</body>
</html>
