{% extends "base.html" %}

{% block title %}New Scan - Malware Website Crawler{% endblock %}

{% block content %}
<div class="row">
    <div class="col-lg-8 mx-auto">
        <div class="card">
            <div class="card-header">
                <h4><i class="fas fa-search"></i> Start New Website Scan</h4>
            </div>
            <div class="card-body">
                <form id="scanForm">
                    <div class="mb-3">
                        <label for="url" class="form-label">Target URL</label>
                        <input type="url" class="form-control" id="url" name="url" 
                               placeholder="https://example.com" required>
                        <div class="form-text">Enter the website URL you want to scan for malware</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="scanType" class="form-label">Scan Type</label>
                        <select class="form-select" id="scanType" name="type">
                            <option value="website">Full Website Crawl</option>
                            <option value="single-page">Single Page Only</option>
                            <option value="deep-scan">Deep Scan (Slower)</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-play"></i> Start Scan
                    </button>
                </form>
            </div>
        </div>

        <!-- Scan Progress -->
        <div class="card mt-4 scan-progress" id="scanProgress">
            <div class="card-header">
                <h5><i class="fas fa-spinner fa-spin"></i> Scan in Progress</h5>
            </div>
            <div class="card-body">
                <div class="progress mb-3">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" 
                         role="progressbar" style="width: 0%"></div>
                </div>
                <div id="scanStatus">Initializing scan...</div>
                <div id="scanDetails" class="mt-2"></div>
            </div>
        </div>

        <!-- Scan Results -->
        <div class="card mt-4" id="scanResults" style="display: none;">
            <div class="card-header">
                <h5><i class="fas fa-shield-alt"></i> Scan Results</h5>
            </div>
            <div class="card-body">
                <div id="resultsSummary"></div>
                <div id="findingsList" class="mt-3"></div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let currentJobId = null;
let statusInterval = null;

document.getElementById('scanForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const url = document.getElementById('url').value;
    const scanType = document.getElementById('scanType').value;
    
    try {
        const response = await axios.post('/api/scan', {
            url: url,
            type: scanType
        });
        
        currentJobId = response.data.job_id;
        showProgress();
        startStatusPolling();
        
    } catch (error) {
        console.error('Error starting scan:', error);
        alert('Error starting scan: ' + (error.response?.data?.error || error.message));
    }
});

function showProgress() {
    document.getElementById('scanProgress').style.display = 'block';
    document.getElementById('scanResults').style.display = 'none';
}

function startStatusPolling() {
    if (statusInterval) {
        clearInterval(statusInterval);
    }
    
    statusInterval = setInterval(async () => {
        try {
            const response = await axios.get(`/api/scan/${currentJobId}`);
            updateProgress(response.data);
            
            if (response.data.job.status === 'completed' || response.data.job.status === 'failed') {
                clearInterval(statusInterval);
                showResults(response.data);
            }
        } catch (error) {
            console.error('Error polling status:', error);
        }
    }, 2000);
}

function updateProgress(data) {
    const progressBar = document.querySelector('.progress-bar');
    const statusDiv = document.getElementById('scanStatus');
    const detailsDiv = document.getElementById('scanDetails');
    
    let progress = 0;
    let status = data.job.status;
    
    switch (status) {
        case 'pending':
            progress = 10;
            status = 'Queued for processing...';
            break;
        case 'running':
            progress = 50;
            status = 'Crawling website and analyzing files...';
            break;
        case 'completed':
            progress = 100;
            status = 'Scan completed successfully!';
            break;
        case 'failed':
            progress = 0;
            status = 'Scan failed';
            break;
    }
    
    progressBar.style.width = progress + '%';
    statusDiv.textContent = status;
    
    if (data.findings && data.findings.length > 0) {
        detailsDiv.innerHTML = `
            <small class="text-muted">
                Found ${data.findings.length} files, analyzing...
            </small>
        `;
    }
}

function showResults(data) {
    document.getElementById('scanProgress').style.display = 'none';
    document.getElementById('scanResults').style.display = 'block';
    
    const summaryDiv = document.getElementById('resultsSummary');
    const findingsDiv = document.getElementById('findingsList');
    
    const findings = data.findings || [];
    const malwareCount = findings.filter(f => f.malware_name).length;
    const suspiciousCount = findings.filter(f => f.confidence > 0.3 && !f.malware_name).length;
    const safeCount = findings.length - malwareCount - suspiciousCount;
    
    summaryDiv.innerHTML = `
        <div class="row text-center">
            <div class="col-md-4">
                <div class="text-danger">
                    <h3>${malwareCount}</h3>
                    <small>Malware Detected</small>
                </div>
            </div>
            <div class="col-md-4">
                <div class="text-warning">
                    <h3>${suspiciousCount}</h3>
                    <small>Suspicious Files</small>
                </div>
            </div>
            <div class="col-md-4">
                <div class="text-success">
                    <h3>${safeCount}</h3>
                    <small>Safe Files</small>
                </div>
            </div>
        </div>
    `;
    
    if (findings.length === 0) {
        findingsDiv.innerHTML = '<p class="text-muted">No files found on the website.</p>';
        return;
    }
    
    findingsDiv.innerHTML = findings.map(finding => `
        <div class="card finding-card ${finding.malware_name ? 'malware' : finding.confidence > 0.3 ? 'suspicious' : 'safe'} mb-3">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-8">
                        <h6 class="card-title">
                            <i class="fas fa-file"></i> ${finding.filename}
                        </h6>
                        <p class="card-text">
                            <small class="text-muted">Hash: ${finding.file_hash}</small>
                        </p>
                        ${finding.malware_name ? `
                            <span class="badge bg-danger">${finding.malware_name}</span>
                        ` : finding.confidence > 0.3 ? `
                            <span class="badge bg-warning">Suspicious (${Math.round(finding.confidence * 100)}%)</span>
                        ` : `
                            <span class="badge bg-success">Safe</span>
                        `}
                    </div>
                    <div class="col-md-4 text-end">
                        <button class="btn btn-sm btn-outline-primary" onclick="showFindingDetails(${finding.id})">
                            <i class="fas fa-info-circle"></i> Details
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

function showFindingDetails(findingId) {
    // This would open a modal with detailed information
    alert('Finding details for ID: ' + findingId);
}
</script>
{% endblock %}
