/**
 * Datasheet Generator
 * Generates formatted test data sheets from database records
 */

/**
 * Generate a datasheet from a test record
 * @param {Object} record - Database record
 * @param {string} format - Output format ('html' or 'txt')
 * @returns {string} Formatted datasheet
 */
function generateDatasheet(record, format = 'html') {
    if (format === 'html') {
        return generateHtmlDatasheet(record);
    } else {
        return generateTextDatasheet(record);
    }
}

/**
 * Generate HTML datasheet
 */
function generateHtmlDatasheet(record) {
    const testDate = formatDate(record.test_date);

    return `<!DOCTYPE html>
<html>
<head>
    <title>Test Data Sheet - ${record.serial_number}</title>
    <style>
        body {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }
        .company {
            font-weight: bold;
        }
        .contact {
            text-align: right;
        }
        h1 {
            text-align: center;
            border-top: 2px solid #333;
            border-bottom: 2px solid #333;
            padding: 10px;
            font-size: 16px;
        }
        .info {
            margin: 20px 0;
        }
        .info-row {
            display: flex;
        }
        .info-label {
            width: 100px;
            font-weight: bold;
        }
        .raw-data {
            background: #f5f5f5;
            padding: 15px;
            border: 1px solid #ddd;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            font-size: 11px;
            overflow-x: auto;
        }
        .result {
            font-size: 18px;
            font-weight: bold;
            text-align: center;
            padding: 10px;
            margin: 20px 0;
        }
        .result.pass { background: #d4edda; color: #155724; }
        .result.fail { background: #f8d7da; color: #721c24; }
        .footer {
            margin-top: 30px;
            border-top: 1px solid #333;
            padding-top: 20px;
            font-size: 10px;
        }
        @media print {
            body { margin: 0; }
            .no-print { display: none; }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="company">
            DATAFORTH CORPORATION<br>
            3331 E. Hemisphere Loop<br>
            Tucson, AZ 85706 USA
        </div>
        <div class="contact">
            Phone: (520) 741-1404<br>
            Fax: (520) 741-0762<br>
            Email: info@dataforth.com
        </div>
    </div>

    <h1>TEST DATA SHEET</h1>

    <div class="info">
        <div class="info-row"><span class="info-label">Date:</span> ${testDate}</div>
        <div class="info-row"><span class="info-label">Model:</span> ${record.model_number}</div>
        <div class="info-row"><span class="info-label">SN:</span> ${record.serial_number}</div>
        <div class="info-row"><span class="info-label">Log Type:</span> ${record.log_type}</div>
        <div class="info-row"><span class="info-label">Station:</span> ${record.test_station || 'N/A'}</div>
    </div>

    <div class="result ${record.overall_result?.toLowerCase() || ''}">
        OVERALL RESULT: ${record.overall_result || 'UNKNOWN'}
    </div>

    <h3>Test Data</h3>
    <div class="raw-data">${escapeHtml(record.raw_data || 'No data available')}</div>

    <div class="footer">
        <p>It is hereby certified that the above product is in conformance with
        all requirements to the extent specified. This product is not
        authorized or warranted for use in life support devices and/or systems.</p>
        <p>Source: ${record.source_file}</p>
        <p>Record ID: ${record.id}</p>
    </div>

    <div class="no-print" style="margin-top: 20px; text-align: center;">
        <button onclick="window.print()">Print Datasheet</button>
        <button onclick="window.close()">Close</button>
    </div>
</body>
</html>`;
}

/**
 * Generate plain text datasheet
 */
function generateTextDatasheet(record) {
    const testDate = formatDate(record.test_date);
    const line = '='.repeat(75);
    const tilde = '~'.repeat(75);

    return `DATAFORTH CORPORATION                         Phone: (520) 741-1404
3331 E. Hemisphere Loop                       Fax:   (520) 741-0762
Tucson, AZ  85706  USA                        Email: info@dataforth.com

                            TEST DATA SHEET
${tilde}
Date:     ${testDate}
Model:    ${record.model_number}
SN:       ${record.serial_number}
Log Type: ${record.log_type}
Station:  ${record.test_station || 'N/A'}

                         OVERALL RESULT: ${record.overall_result || 'UNKNOWN'}

${line}
                              TEST DATA
${line}

${record.raw_data || 'No data available'}

${line}

It is hereby certified that the above product is in conformance with
all requirements to the extent specified. This product is not
authorized or warranted for use in life support devices and/or systems.

Source: ${record.source_file}
Record ID: ${record.id}
`;
}

/**
 * Format date for display
 */
function formatDate(dateStr) {
    if (!dateStr) return 'Unknown';
    // Convert YYYY-MM-DD to MM-DD-YYYY
    const [year, month, day] = dateStr.split('-');
    return `${month}-${day}-${year}`;
}

/**
 * Escape HTML special characters
 */
function escapeHtml(str) {
    if (!str) return '';
    return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

module.exports = { generateDatasheet };
