package com.microsoft.graph.functional;

import com.microsoft.graph.authentication.IAuthenticationProvider;
import com.microsoft.graph.core.DefaultClientConfig;
import com.microsoft.graph.core.IClientConfig;
import com.microsoft.graph.http.IHttpRequest;
import com.microsoft.graph.models.extensions.IGraphServiceClient;
import com.microsoft.graph.models.extensions.GraphServiceClient;
import com.microsoft.graph.core.Constants;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;


public class TestBase {
    private String clientId;
    private String username;
    private String password;
    // Don't use password grant in your apps. Only use for legacy solutions and automated testing.
    private String grantType = "password";
    private String tokenEndpoint = "https://login.microsoftonline.com/common/oauth2/token";
    private String resourceId = "https%3A%2F%2Fgraph.microsoft.com%2F";
    private String accessToken = null;

    protected IGraphServiceClient graphClient = null;

    public TestBase()
    {
        clientId = Constants.APPID;
        username = Constants.USERNAME;
        password = Constants.PASSWORD;

        GetAuthenticatedClient();
    }

    private void GetAuthenticatedClient()
    {
        if (graphClient == null) {
            try {
                accessToken = GetAccessToken();
                IAuthenticationProvider mAuthenticationProvider = new IAuthenticationProvider() {
                    @Override
                    public void authenticateRequest(final IHttpRequest request) {
                        request.addHeader("Authorization",
                                "Bearer " + accessToken);
                    }
                };
                IClientConfig mClientConfig = DefaultClientConfig.createWithAuthenticationProvider(mAuthenticationProvider);

                graphClient = new GraphServiceClient.Builder().fromConfig(mClientConfig).buildClient();
            }
            catch (Exception e)
            {
                throw new Error("Could not create a graph client: " + e.getLocalizedMessage());
            }
        }
    }

    private String GetAccessToken()
    {

        try {
            URL url = new URL(tokenEndpoint);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            String line;
            StringBuilder jsonString = new StringBuilder();

            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            String payload = String.format("grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s",
                    grantType,
                    resourceId,
                    clientId,
                    username,
                    password);
            writer.write(payload);
            writer.close();
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while((line = br.readLine()) != null){
                    jsonString.append(line);
                }
                br.close();
            } catch (Exception e) {
                throw new Error("Error reading authorization response: " + e.getLocalizedMessage());
            }
            conn.disconnect();

            JSONObject res = new JSONObject(jsonString.toString());
            return res.get("access_token").toString();

        } catch (Exception e) {
            throw new Error("Error retrieving access token: " + e.getLocalizedMessage());
        }
    }
}
@@ -1977,20 +1977,16 @@
 Client =
- new
  GraphSe
@@ -1997,17 +1997,17 @@
 eClient.
-B
+b
 uilder()

update unit test to use GraphServiceClient.builder()