package org.aslak.github.merge.service;

import java.util.HashSet;
import java.util.Set;

import javax.enterprise.context.ApplicationScoped;

import org.aslak.github.merge.model.PullRequest;
import org.aslak.github.merge.rest.GithubUtil;
import org.kohsuke.github.GitHub;

@ApplicationScoped
public class PullRequestService {

    private Set<PullRequest> store;
    
    public PullRequestService() {
        this.store = new HashSet<>();
    }

    public PullRequest get(String user, String repo, int pull) {
        PullRequest request = locate(user, repo, pull);
        if(request == null) {
            request = fetch(user, repo, pull);
            store(request);
        }
        return request;
    }
    
    private PullRequest fetch(String user, String repo, int pull) {
        try {
            return GithubUtil.toPullRequest(
                    GitHub.connectAnonymously()
                        .getOrganization(user)
                        .getRepository(repo)
                        .getPullRequest(pull));

        } catch (Exception e) {
            throw new RuntimeException("Could not fetch PullRequest from GitHub for " + user + "/" + repo + "/" + pull, e);
        }
    }

    private PullRequest locate(String user, String repo, int pull) {
        for(PullRequest request : store) {
            if(
                    request.getTarget().getUser().equals(user) &&
                    request.getTarget().getRepository().equals(repo) &&
                    request.getNumber() == pull) {
                return request;
            }
        }
        return null;
    }
    
    public void store(PullRequest pullrequest) {
        this.store.add(pullrequest);
    }

    public void delete(PullRequest pullRequest) {
        this.store.remove(pullRequest);
    }
}

@@ -134,16 +134,93 @@
 Scoped;%0A
+import javax.inject.Inject;%0A%0Aimport org.aslak.github.merge.model.CurrentUser;
 %0Aimport 
@@ -432,16 +432,66 @@
 %3E store;
+%0A%0A    @Inject%0A    private CurrentUser currentUser;
 %0A    %0A  
@@ -829,28 +829,24 @@
 uest;%0A    %7D%0A
-    
 %0A    private
@@ -932,88 +932,275 @@
     
-return GithubUtil.toPullRequest(%0A                    GitHub.connectAnonymously()
+GitHub github;%0A            if(currentUser== null) %7B%0A                github = GitHub.connectAnonymously();%0A            %7D else %7B%0A                github = GitHub.connectUsingOAuth(currentUser.getAccessToken());%0A            %7D%0A%0A            return GithubUtil.toPullRequest(
 %0A   
@@ -1216,24 +1216,30 @@
             
+github
 .getOrganiza
@@ -1269,24 +1269,28 @@
             
+    
 .getReposito
@@ -1298,16 +1298,20 @@
 y(repo)%0A
+    
         

Use current users auth to fetch GitHub info