package org.jbehave.web.selenium;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.commons.io.IOUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

/**
 * Delegating abstract implementation that provides {@link WebDriver}s specified
 * by the concrete delegate.
 */
public abstract class DelegatingWebDriverProvider implements WebDriverProvider {

    protected ThreadLocal<WebDriver> delegate = new ThreadLocal<WebDriver>();

    public WebDriver get() {
        WebDriver webDriver = delegate.get();
        if (webDriver == null) {
            throw new NullPointerException("WebDriver not setup yet for this thread. Are you using the right one of PerScenarioWebDriverSteps, PerStoryWebDriverSteps and PerStoriesWebDriverSteps");
        }
        return webDriver;
    }

    public boolean saveScreenshotTo(String path) {
        WebDriver driver = get();
        if (driver instanceof TakesScreenshot) {
            File file = new File(path);
            try {
                file.getParentFile().mkdirs();
                file.createNewFile();
                byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
                IOUtils.write(bytes, new FileOutputStream(file));
                return true;
            } catch ( Exception e) {
                throw new RuntimeException("Failed to save screenshot to " + file, e);
            }
        }
        return false;
    }

}
@@ -646,53 +646,418 @@
     
-throw new NullPointerException(%22WebDriver not
+String msg = %22***  WebDriver has not initialized.  This either because the initialize() method of %22 + this.getClass().getName() + %22 failed.%5Cn%22%0A                    + %22Refer the build log for error message/exceptions previously sent.%5Cn%22%0A                    + %22Refer also http://jira.codehaus.org/browse/JBEHAVE-400) for who the build is not halted sooner.%5Cn%22%0A                    + %22OR WebDriver may not have been
  set
@@ -1108,14 +1108,19 @@
 ght 
-one of
+impl class:
  Per
@@ -1141,17 +1141,23 @@
 verSteps
-,
+ versus
  PerStor
@@ -1176,11 +1176,14 @@
 eps 
-and
+versus
  Per
@@ -1207,46 +1207,356 @@
 teps
-%22);%0A        %7D%0A        return webDriver
+?%22;%0A            banner(); banner(); banner();%0A            System.out.println(msg);%0A            banner(); banner(); banner();%0A            throw new NullPointerException(msg);%0A        %7D%0A        return webDriver;%0A    %7D%0A%0A    private void banner() %7B%0A        System.out.println(%22*************************************************************************%22)
 ;%0A  

improve reporting around WebDriverProvider initializtion errors