const { Eyes, Target } = require('@applitools/eyes-selenium');
const { Builder, Capabilities } = require('selenium-webdriver');
const webdriver = require('selenium-webdriver');

// Set the value of changeTest to true to introduce changes that Eyes will detect as mismatches
var changeTest = false;
var weburl = "https://applitools.com/helloworld/";
var resultStr = "";

function main() {
    const eyes = new Eyes();

    // Set your Applitools API key
    eyes.setApiKey('BclMh7CJCqgZxqNLsdNMch1043nGszNOzqFHpH0UoXfvg110');

    // Setup Webdriver
    const driver = new webdriver.Builder()
        .withCapabilities(Capabilities.chrome())
        .build();

    if(!changeTest){
        test01(eyes, driver);
    }else{
        test02(eyes, driver);
    }
}

async function test01(eyes, driver){
    try {
        // Open Eyes Session
        await eyes.open(driver, 'Web App', 'Visual Test by Applitools');

        // Capture Visual Checkpoints
        await driver.get(weburl);
        await eyes.check("Before mouse click", Target.window());
        
        // Capture Visual Checkpoints
        await driver.findElement(webdriver.By.css("button")).click(); // Click the button
        await eyes.check("After mouse click", Target.window()); 

        // Close Eyes Session and handle test results
        eyes.close(false).then(function (result){ 
            handleTestResults(result);
        });
    } finally {
        // Close Webdriver
        await driver.quit();
    }
}

async function test02(eyes, driver){
    try {
        // Open Eyes Session
        await eyes.open(driver, 'Web App', 'Visual Test by Applitools');

        // Capture Visual Checkpoints
        await driver.get(weburl+"?diff2");
        await eyes.check("Before mouse click", Target.window());
        
        // Capture Visual Checkpoints
        await driver.findElement(webdriver.By.css("button")).click(); // Click the button
        await eyes.check("After mouse click", Target.window()); 

        // Close Eyes Session and handle test results
        eyes.close(false).then(function (result){ 
            handleTestResults(result);
        });
    } finally {
        // Close Webdriver
        await driver.quit();
    }
}

function handleTestResults(result) {
    var url = result.appUrls.session;
    var totalSteps = result.steps;

    if (result.isNew) {
        resultStr = "New Baseline Created:      " + totalSteps + " steps";
    } else if (result.isDifferent) {
        resultStr = "Test Failed:   ";
        resultStr += " matches=" +  result.matches;      /* matched the baseline */
        resultStr += " mismatches=" + result.mismatches; /* did not match the baseline */
    } else {
        resultStr = "All steps passed:     " + totalSteps + " steps";
    } 
    resultStr += "\n" + "results at " + url; 
    console.log(resultStr); 
}

main();