{% extends "base.html" %}

{% block title %}Submit Test Job - ASF TestArena{% endblock %}

{% block content %}
<div class="submit-container">
    <h2 style="margin-bottom: 30px; color: var(--dark);">Submit New Test Job</h2>
    
    <div class="step-indicator">
        <div class="step active">
            <div class="step-number">1</div>
            <div class="step-label">Branch</div>
        </div>
        <div class="step">
            <div class="step-number">2</div>
            <div class="step-label">Scenarios</div>
        </div>
        <div class="step">
            <div class="step-number">3</div>
            <div class="step-label">Environment</div>
        </div>
        <div class="step">
            <div class="step-number">4</div>
            <div class="step-label">Test Mode</div>
        </div>
        <div class="step">
            <div class="step-number">5</div>
            <div class="step-label">Review</div>
        </div>
    </div>
    
    <form id="branchForm">
        <div class="form-group">
            <label for="branch_name">Git Branch Name</label>
            <input type="text" id="branch_name" name="branch_name" class="form-control" 
                   placeholder="e.g., feature/new-feature" required>
            <small style="color: #6b7280; margin-top: 5px; display: block;">
                Enter the branch name to analyze available test scenarios
            </small>
            
            <div id="branchValidation" class="branch-validation">
                <div class="loading-spinner"></div>
                <span id="validationMessage">Validating branch...</span>
            </div>
        </div>
        
        <div class="form-actions">
            <a href="{{ url_for('dashboard.index') }}" class="btn" style="background: #6b7280; color: white;">Cancel</a>
            <button type="submit" id="validateBtn" class="btn btn-primary">Validate Branch</button>
            <button type="button" id="nextBtn" class="btn btn-primary" style="display: none;" onclick="proceedToStep2()">Next</button>
        </div>
    </form>
</div>

<script>
let validatedBranch = null;
let organizedData = {};
let scenarioMap = {};

document.getElementById('branchForm').addEventListener('submit', function(e) {
    e.preventDefault();
    validateBranch();
});

function validateBranch() {
    const branchName = document.getElementById('branch_name').value.trim();
    
    if (!branchName) {
        alert('Please enter a branch name');
        return;
    }
    
    // Show loading state
    const validation = document.getElementById('branchValidation');
    const message = document.getElementById('validationMessage');
    const validateBtn = document.getElementById('validateBtn');
    const nextBtn = document.getElementById('nextBtn');
    
    validation.className = 'branch-validation loading';
    validation.style.display = 'block';
    message.textContent = 'Validating branch...';
    validateBtn.disabled = true;
    nextBtn.style.display = 'none';
    
    // Make AJAX request
    fetch('/jobs/submit/step1', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `branch_name=${encodeURIComponent(branchName)}`
    })
    .then(response => response.json())
    .then(data => {
        console.log('Branch validation response:', data); // Debug log
        
        if (data.success) {
            // Success
            validation.className = 'branch-validation success';
            message.textContent = data.message;
            validateBtn.style.display = 'none';
            nextBtn.style.display = 'inline-block';
            
            validatedBranch = branchName;
            organizedData = data.organized_data || {};
            scenarioMap = data.scenario_map || {};
            
            // Log debug info
            if (data.debug) {
                console.log('Debug info:', data.debug);
            }
            if (data.output) {
                console.log('Command output:', data.output);
            }
        } else {
            // Error
            validation.className = 'branch-validation error';
            message.textContent = data.error;
            validateBtn.disabled = false;
            nextBtn.style.display = 'none';
            
            validatedBranch = null;
            organizedData = {};
            scenarioMap = {};
            
            // Log debug info for troubleshooting
            console.error('Branch validation failed:', data.error);
            if (data.debug) {
                console.error('Debug info:', data.debug);
            }
            if (data.output) {
                console.error('Command output:', data.output);
            }
        }
    })
    .catch(error => {
        // Network error
        validation.className = 'branch-validation error';
        message.textContent = 'Network error. Please try again.';
        validateBtn.disabled = false;
        nextBtn.style.display = 'none';
        
        validatedBranch = null;
        availableScenarios = [];
    });
}

function proceedToStep2() {
    if (!validatedBranch || Object.keys(organizedData).length === 0) {
        alert('Please validate the branch first');
        return;
    }
    
    // Create form to submit to step 2
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '/jobs/submit/step2-validated';
    
    const branchInput = document.createElement('input');
    branchInput.type = 'hidden';
    branchInput.name = 'branch_name';
    branchInput.value = validatedBranch;
    form.appendChild(branchInput);
    
    const organizedDataInput = document.createElement('input');
    organizedDataInput.type = 'hidden';
    organizedDataInput.name = 'organized_data';
    organizedDataInput.value = JSON.stringify(organizedData);
    form.appendChild(organizedDataInput);
    
    const scenarioMapInput = document.createElement('input');
    scenarioMapInput.type = 'hidden';
    scenarioMapInput.name = 'scenario_map';
    scenarioMapInput.value = JSON.stringify(scenarioMap);
    form.appendChild(scenarioMapInput);
    
    document.body.appendChild(form);
    form.submit();
}

// Reset validation when branch name changes
document.getElementById('branch_name').addEventListener('input', function() {
    const validation = document.getElementById('branchValidation');
    const validateBtn = document.getElementById('validateBtn');
    const nextBtn = document.getElementById('nextBtn');
    
    validation.style.display = 'none';
    validateBtn.style.display = 'inline-block';
    validateBtn.disabled = false;
    nextBtn.style.display = 'none';
    
    validatedBranch = null;
    organizedData = {};
    scenarioMap = {};
});
</script>
{% endblock %}
