import nodemailer from 'nodemailer';
import DateFormat from '../core/dateFormatUtil.js';

export default class FastReportService {
    constructor(options = {}, capabilities, config) {
        this.options = options
        this.transport = nodemailer.createTransport(this.options.transportOptions);
    }

    // This is called after the session has been created
    beforeSession() {
        // Nothing to do here for this service
    }

    // This is called after the browser has been initialized
    before() {
        // Nothing to do here for this service
    }

    // This is called after a test has completed
    afterTest(test, context, { error, result, duration, passed, retries }) {
        try {
            if (error) {
                if (browser.config.currentstepMeta.fastReport) {
                    if (this.options.timeInterval) {
                        if (DateFormat.timeInsideIntervalAndTimeZoneAndBusinessDay(this.options.timeInterval)) {
                            console.log('Start generating report, fast report enabled in interval: ' + this.options.timeInterval)
                            this.sendEmailReport(test, error, duration);
                        }else{
                            console.log('Outside of defined time interval for fast report : '+ this.options.timeInterval)
                        }
                    }else{
                        console.log('Start generating report, fast report enabled , no time interval defined')
                        this.sendEmailReport(test, error, duration);
                    }
                }
            }

        } catch (error) {
            console.log('Fast report error: ', error)
        }
    }
    // This is called after all tests are done
    after() {
        // Nothing to do here for this service
    }

    // This is called after the session has ended
    afterSession() {
        // Nothing to do here for this service
    }

    // Send email report with the failures
    async sendEmailReport(test, error, duration) {
        console.log(`Sending fast report email for failed tests`);

        try {
            // Generate the email content
            const { textContent, htmlContent } = await this.generateEmailContent(test, error, duration);
            // Prepare the email message
            const message = {
                from: this.options.from,
                to: this.options.to,
                bcc: this.options.bcc,
                subject: `${this.options.subjectPrefix}: ` + test.parent + ' step: ' + test.title + ' failed. ',
                text: textContent,
                html: htmlContent
            };

            // Send the email
            this.transport.sendMail(message, (err, info) => {
                if (err) {
                    console.error('Failed to send fast report email:', err);
                } else {
                    console.log('Fast report email sent successfully:', info.messageId);
                }
            });
        } catch (error) {
            console.error('Error preparing or sending fast report email:', error);
        }
    }

    // Generate the email content in both text and HTML formats
    async generateEmailContent(test = '', error = '', duration = '') {
        // Get the test run info
        const runInfo = {
            timestamp: new Date().toISOString(),
            browser: browser.capabilities.browserName,
            platform: browser.capabilities.platformName || 'unknown',
            userName: browser.config.loggedInUser,
            lastUrl: await browser.getUrl(),
            env: browser.config.env,
            duration: duration/1000
        };

        // Generate plain text email
        let textContent = `Test Failure Report\n`;
        textContent += `====================\n\n`;
        textContent += `Report Date: ${new Date(runInfo.timestamp).toLocaleString()}\n`;
        textContent += `Browser: ${runInfo.browser}\n`;
        textContent += `Platform: ${runInfo.platform}\n`;
        textContent += `Environment: ${runInfo.env}\n`;
        textContent += `Username: ${runInfo.userName}\n`;
        textContent += `Step duration: ${runInfo.duration}(s)\n`;
        textContent += `LastUrl: ${runInfo.lastUrl}\n\n`;

        if(this.options.userTagList){
            textContent += `Tag Users:\n`;
            for(let user of this.options.userTagList){
                textContent += `@${user}`;
            }
        }
        textContent += `\n\n ==================== \n\n`;
        const testTitle = test.title;
        const testParent = test.parent;
        const errorMessage = error ? error.message : 'Unknown error';

        textContent += `   Describe: ${testParent}\n`;
        textContent += `   Step: ${testTitle}\n`;
        textContent += `   Error: ${errorMessage}\n`;
        textContent += `   FullError: ${error}\n`;

        textContent += `\n`;


        // Generate HTML email
        let htmlContent = `
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 0 auto; }
                    h1 { color: #c00; border-bottom: 1px solid #ddd; padding-bottom: 10px; }
                    .info-section { background-color: #f8f8f8; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
                    .failure { margin-bottom: 25px; border-left: 4px solid #c00; padding-left: 15px; }
                    .failure-header { font-weight: bold; font-size: 16px; margin-bottom: 5px; }
                    .failure-details { margin-left: 10px; color: #555; }
                    .error-message { color: #c00; margin-top: 10px; font-family: monospace; white-space: pre-wrap; }
                    .meta-data { margin-top: 10px; font-size: 14px; color: #666; }
                    .meta-item { margin-bottom: 5px; }
                </style>
            </head>
            <body>
                <h1>Test Failure Report</h1>
                
                <div class="info-section">
                    <p><strong>Date:</strong> ${new Date(runInfo.timestamp).toLocaleString()}</p>
                    <p><strong>Browser:</strong> ${runInfo.browser}</p>
                    <p><strong>Platform:</strong> ${runInfo.platform}</p>
                    <p><strong>Environment:</strong> ${runInfo.env}</p>
                    <p><strong>User Name:</strong> ${runInfo.userName}</p>
                    <p><strong>Step duration (s):</strong> ${runInfo.duration}</p>
                    <p><strong>Last Url:</strong> ${runInfo.lastUrl}</p>
                </div>
        `;

        // Add failure to the HTML content

        htmlContent += `
                <div class="failure">
                    <div class="failure-header"> ${testParent} - ${testTitle}</div>
                    <div class="failure-details">
                        <div class="error-message">${errorMessage}</div>
                         <div class="error-">${error}</div>
                        <div class="meta-data">
            `;
        htmlContent += `
                        </div>
                    </div>
                </div>
            `;


        // Close the HTML structure
        htmlContent += `
            </body>
            </html>
        `;

        return { textContent, htmlContent };
    }
} 