{% extends "users/base.html" %}
{% block title %}{% if edit_mode %}Edit {{ name }}{% else %}Add {{ name }}{% endif %}{% endblock title %}
{% block content %}

<div id="responseContainer" style="position: relative; display: none;"> <!-- Container for the response -->
        <nav aria-label="breadcrumb">
                  <ol class="breadcrumb breadcrumb-inverse">
                   
           <li class="breadcrumb-item active" aria-current="page" style="margin-top:10px">Action running, please wait.....</li> 
			<li> <div class="sk-wave">
            <div class="rect1"></div>
            <div class="rect2"></div>
            <div class="rect3"></div>
            <div class="rect4"></div>
            <div class="rect5"></div>
          
        </div>
</li> 
       </ol>
                </nav>
    </div>
	
<div class="card card-default">
    <div class="card-header">
        <h2>{% if edit_mode %}Edit {{ name }}{% else %}Add {{ name }}{% endif %}</h2>
    </div>
    <div class="card-body">
        <form method="post" action="">
            {% csrf_token %}
			{% if edit_mode %}
<div class="form-group">
			
            <!-- Submit Button -->
         
              <button id="install" onclick="restart()" class="btn btn-outline-success">
                   <i class="mdi mdi-restart"></i> Restart app  
			
			
                </button>
				
			<button id="install" onclick="npm_install()" class="btn btn-outline-primary">
                   <i class="mdi mdi-play"></i> Run NPM Install  
			
			
                </button>

				
				
            </div>
			<div id="alertContainer" class="alert alert-success alert-dismissible fade show" role="alert" style="display: none;">
    <div id="message"></div>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                  <span aria-hidden="true">×</span>
                </button>
</div>	
			{% endif %}
            <!-- Select Domain -->
            <div class="col-md-5 mb-3">
                <label class="small mb-1" for="domainx">Select Domain:</label>
                <div class="form-group">
                    <select class="form-control" name="domain_name" id="domainx" {% if edit_mode %}disabled{% endif %}>
                        {% for domain in domains %}
                            <option value="{{ domain.domain }}" 
                                {% if edit_mode and app.domain_id == domain.id %}
                                    selected
                                {% elif not edit_mode and forloop.first %}
                                    selected
                                {% endif %}>
                                {{ domain.domain }}
                            </option>
                        {% endfor %}
                    </select>
                </div>
            </div>

            <!-- Select App Version -->
            <div class="col-md-5 mb-3">
                <label class="small mb-1" for="app_version">Select {{ name }} Version:</label>
                <div class="form-group">
                    <select class="form-control" name="app_version" id="app_version">
                        {% for app_version in app_versions %}
                            <option value="{{ app_version }}" 
                                {% if edit_mode and app.version == app_version %}
                                    selected
                                {% elif not edit_mode and forloop.first %}
                                    selected
                                {% endif %}>
                                {{ app_version }}
                            </option>
                        {% endfor %}
                    </select>
                </div>
            </div>

            <!-- Document Root -->
            <div class="col-md-5 mb-3">
                <label class="small mb-1" for="path">Document Root (File System Location):</label>
                <div class="input-group mb-2 mr-sm-2">
                    <div class="input-group-prepend">
                        <div class="input-group-text"><span class="mdi mdi-home"></span></div>
                    </div>
                    <input type="text" id="path" name="target_name" class="form-control"
                           value="{% if edit_mode %}{{ app_path }}{% else %}{{ target_name_simple }}{% endif %}">
                </div>
            </div>

            <!-- Startup File -->
            <div class="col-md-5 mb-3">
                <label class="small mb-1" for="startup_file">Startup file (eg: app.js):</label>
                <div class="input-group mb-2 mr-sm-2">
                    <input type="text" id="startup_file" name="startup_file" class="form-control"
                           value="{% if edit_mode %}{{ app.startup_file }}{% else %}{{ startup_file }}{% endif %}">
                </div>
            </div>
			
			   <div class="form-group">
			
            <!-- Submit Button -->
         
                <button type="submit" id="save" class="btn btn-outline-success mt-3">
                    <i class="mdi mdi-content-save"></i> {% if edit_mode %}Update {{ name }}{% else %}Add {{ name }}{% endif %}
                </button>
				
				
				
            </div>
			
			
			
			
        </form>
    </div>
</div>
<!-- Hidden values for edit mode -->
<input type="hidden" id="selected_domain" value="{% if edit_mode %}{{ app.domain.domain }}{% endif %}">
<input type="hidden" id="selected_version" value="{% if edit_mode %}{{ app.version }}{% endif %}">

<script>
document.addEventListener("DOMContentLoaded", function () {
    let selectedDomain = document.getElementById("selected_domain").value;
    let selectedVersion = document.getElementById("selected_version").value;

    // Select Domain
    if (selectedDomain) {
        let domainSelect = document.getElementById("domainx");
        for (let opt of domainSelect.options) {
            if (opt.value === selectedDomain) {
                opt.selected = true;
                break;
            }
        }
    }

    // Select App Version
    if (selectedVersion) {
        let versionSelect = document.getElementById("app_version");
        for (let opt of versionSelect.options) {
            if (opt.value === selectedVersion) {
                opt.selected = true;
                break;
            }
        }
    } else {
        // If adding new → select first option by default
        document.getElementById("app_version").selectedIndex = 0;
    }
});

{% if edit_mode %}
function restart() {
    event.preventDefault();
       
        const responseDisplay = document.getElementById('responseContainer');
        const alertContainer = document.getElementById('alertContainer');
        const messageDisplay = document.getElementById('message');

        setTimeout(function() {
            responseDisplay.style.display = 'inline-block';

            // Call the URL (replace '/your-url' with your actual URL)
            fetch('{% url 'restart_node' app.id %}', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.statusText);
                }
                return response.text(); // Retrieve response as plain text
            })
            .then(data => {
                console.log('Response:', data);
                responseDisplay.style.display = 'none';

                if (data.includes('success')) {
                    // Set alert for success
                    alertContainer.className = "alert alert-success alert-dismissible fade show";
                    messageDisplay.innerText = "restart success full"; // Displaying success message
                } else {
                    // Set alert for error
                    alertContainer.className = "alert alert-danger alert-dismissible fade show";
                    messageDisplay.innerText = "restart failed"; // Displaying error message
                }

                alertContainer.style.display = "block";
               

            })
            .catch(error => {
                console.error('Error:', error);
            });
        }, 0); // 1000 milliseconds = 1 second

    
}




function npm_install() {
    event.preventDefault();
       
        const responseDisplay = document.getElementById('responseContainer');
        const alertContainer = document.getElementById('alertContainer');
        const messageDisplay = document.getElementById('message');

        setTimeout(function() {
            responseDisplay.style.display = 'inline-block';

            // Call the URL (replace '/your-url' with your actual URL)
            fetch('{% url 'install_npm' app.id %}', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.statusText);
                }
                return response.text(); // Retrieve response as plain text
            })
            .then(data => {
               // console.log('Response:', data);
                responseDisplay.style.display = 'none';

                if (data.includes('success')) {
                    // Set alert for success
                    alertContainer.className = "alert alert-success alert-dismissible fade show";
                    messageDisplay.innerText = "Run success fully"; // Displaying success message
                } else {
                   try {
        data = JSON.parse(data);
    } catch (e) {
        console.error('Invalid JSON:', e, data);
        alertContainer.className = "alert alert-danger alert-dismissible fade show";
        messageDisplay.innerText = "Invalid server response";
        alertContainer.style.display = "block";
        return;
    }
                    alertContainer.className = "alert alert-danger alert-dismissible fade show";
                    messageDisplay.innerText = data.message || "An error occurred"; // Displaying error message
                }

                alertContainer.style.display = "block";
               

            })
            .catch(error => {
                console.error('Error:', error);
            });
        }, 0); // 1000 milliseconds = 1 second

    
}




{% endif %}
</script>
{% include "users/footer.html" %}
{% endblock content %}
