package org.jbehave.web.selenium;

import org.jbehave.core.model.Story;
import org.jbehave.core.reporters.NullStoryReporter;
import org.openqa.selenium.remote.SessionId;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;

import static org.jbehave.web.selenium.SauceWebDriverProvider.getSauceAccessKey;
import static org.jbehave.web.selenium.SauceWebDriverProvider.getSauceUser;

public class SauceContextStoryReporter extends NullStoryReporter {

    private final WebDriverProvider webDriverProvider;

    private ThreadLocal<String> storyName = new ThreadLocal<String>();
    private ThreadLocal<SessionId> sessionId = new ThreadLocal<SessionId>();
    private ThreadLocal<Boolean> passed = new ThreadLocal<Boolean>();

    public SauceContextStoryReporter(WebDriverProvider webDriverProvider) {
        this.webDriverProvider = webDriverProvider;
    }

    @Override
    public void beforeStory(Story story, boolean givenStory) {
        storyName.set(story.getName());
        passed.set(true);
    }

    @Override
    public void beforeScenario(String title) {
        sessionId.set(((RemoteWebDriverProvider.ScreenShottingRemoteWebDriver) webDriverProvider.get()).getSessionId());
    }

    @Override
    public void failed(String step, Throwable cause) {
        passed.set(false);
    }

    @Override
    public void afterStory(boolean givenStory) {
        if (sessionId.get() != null) {
            try {
                String payload = "{\"tags\":[" + getJobTags() + "], \"passed\":\"" + passed.get() + "\",\"name\":\" " + getJobName() + "\"}";

                URL url = new URL("http://saucelabs.com/rest/v1/" + getSauceUser() + "/jobs/" + sessionId.get().toString());

                Authenticator.setDefault(new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(getSauceUser(), getSauceAccessKey().toCharArray());
                    }
                });

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("PUT");

                OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
                writer.write(payload);
                writer.close();

                System.out.println("Sauce Job update return code: " + connection.getResponseCode());
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String s;
                while ((s = reader.readLine()) != null) {
                    System.out.println(s);
                }
            } catch (IOException e) {
                System.err.println("Error " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.err.println("RemoteWebDriver reporting null session ID");
        }
    }

    /**
     * The name of the job. By default this is the story name.
     * @return the job name
     */
    protected String getJobName() {
        return storyName.get();
    }

    /**
     * A set of tags to apply to the job, like so:
     *   "foo", "bar"
     *
     * @return a string of comma separated strings in quotes
     */
    protected String getJobTags() {
        return "";
    }
}

@@ -418,16 +418,80 @@
 net.URL;
+%0Aimport java.util.regex.Matcher;%0Aimport java.util.regex.Pattern;
 %0A%0Aimport
@@ -1629,51 +1629,8 @@
 ) %7B%0A
-        if (sessionId.get() != null) %7B%0A    
     
@@ -1647,28 +1647,24 @@
             
- 
-   
 String paylo
@@ -1790,20 +1790,16 @@
         
-    
 URL url 
@@ -1896,28 +1896,24 @@
 String());%0A%0A
-    
             
@@ -1975,20 +1975,16 @@
         
-    
 protecte
@@ -2034,28 +2034,24 @@
 ication() %7B%0A
-    
             
@@ -2156,34 +2156,26 @@
             
-   
- 
 %7D%0A
-    
             
@@ -2175,28 +2175,24 @@
        %7D);%0A%0A
-    
             
@@ -2268,36 +2268,32 @@
 ();%0A            
-  
-  
 connection.setDo
@@ -2306,20 +2306,16 @@
 (true);%0A
-    
         
@@ -2351,28 +2351,24 @@
 od(%22PUT%22);%0A%0A
-    
             
@@ -2457,28 +2457,24 @@
             
- 
-   
 writer.write
@@ -2492,28 +2492,24 @@
             
-    
 writer.close
@@ -2529,96 +2529,75 @@
     
-    
-System.out.println(%22Sauce Job update return code: %22 + connection.getResponseCode());
+int rc = connection.getResponseCode();%0A            if (rc == 200) %7B
 %0A   
@@ -2730,16 +2730,234 @@
 tring s;
+%0A%0A                // This comes back from Saucelabs:%0A                // %22video_url%22: %22http://saucelabs.com/jobs/3bd32831ec0d91c423552330b332a59c4/video.flv%22,%0A                Pattern p = Pattern.compile(%22http.*%5C%5C.flv%22);
 %0A       
@@ -3031,26 +3031,35 @@
     
-System.out.println
+Matcher matcher = p.matcher
 (s);
@@ -3064,33 +3064,24 @@
 );%0A         
-       %7D%0A
             
@@ -3083,35 +3083,38 @@
     
- %7D catch (IOException e) %7B%0A
+while (matcher.find()) %7B%0A     
     
@@ -3121,34 +3121,37 @@
             
+   
 System.
-err
+out
 .println(%22Er
@@ -3152,177 +3152,284 @@
 ln(%22
-Error %22 + e.getMessage());%0A                e.printStackTrace();%0A            %7D%0A        %7D else %7B%0A            System.err.println(%22RemoteWebDriver reporting null session ID%22
+Saucelabs Video: %22 + matcher.group());%0A                        break;%0A                    %7D%0A                %7D%0A            %7D%0A        %7D catch (IOException e) %7B%0A            System.err.println(%22Error updating Saucelabs job info: %22 + e.getMessage());%0A            e.printStackTrace(
 );%0A 

print out saucelabs video url