/*
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples;

import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.jobs.v3.CloudTalentSolution;
import com.google.api.services.jobs.v3.model.Company;
import com.google.api.services.jobs.v3.model.ListCompaniesResponse;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

/** The quickstart for Cloud Job Discovery */
public class JobServiceQuickstart {

  // [START quickstart]

  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport NET_HTTP_TRANSPORT = new NetHttpTransport();
  private static final String SCOPES = "https://www.googleapis.com/auth/jobs";
  private static final String DEFAULT_PROJECT_ID =
      "projects/" + System.getenv("GOOGLE_CLOUD_PROJECT");

  private static CloudTalentSolution talentSolutionClient =
      createTalentSolutionClient(generateCredential());

  private static CloudTalentSolution createTalentSolutionClient(GoogleCredentials credential) {
    String url = "https://jobs.googleapis.com";
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
    return new CloudTalentSolution.Builder(
            NET_HTTP_TRANSPORT, JSON_FACTORY, setHttpTimeout(requestInitializer))
        .setApplicationName("JobServiceClientSamples")
        .setRootUrl(url)
        .build();
  }

  private static GoogleCredentials generateCredential() {
    try {
      // Credentials could be downloaded after creating service account
      // set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable, for example:
      // export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json
      return GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(SCOPES));
    } catch (Exception e) {
      System.out.print("Error in generating credential");
      throw new RuntimeException(e);
    }
  }

  private static HttpRequestInitializer setHttpTimeout(
      final HttpRequestInitializer requestInitializer) {
    return request -> {
      requestInitializer.initialize(request);
      request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
      request.setConnectTimeout(1 * 60000); // 1 minute connect timeout
      request.setReadTimeout(1 * 60000); // 1 minute read timeout
    };
  }

  public static CloudTalentSolution getTalentSolutionClient() {
    return talentSolutionClient;
  }

  public static void main(String... args) throws Exception {
    try {
      ListCompaniesResponse listCompaniesResponse =
          talentSolutionClient.projects().companies().list(DEFAULT_PROJECT_ID).execute();
      System.out.println("Request Id is " + listCompaniesResponse.getMetadata().getRequestId());
      if (listCompaniesResponse.getCompanies() != null) {
        for (Company company : listCompaniesResponse.getCompanies()) {
          System.out.println(company.getName());
        }
      }
    } catch (IOException e) {
      System.out.println("Got exception while listing companies");
      throw e;
    }
  }

  // [END quickstart]
}

@@ -617,55 +617,8 @@
 s;%0A%0A
-import com.google.api.client.http.HttpHeaders;%0A
 impo
@@ -893,24 +893,90 @@
 ntSolution;%0A
+import com.google.api.services.jobs.v3.CloudTalentSolutionScopes;%0A
 import com.g
@@ -1514,87 +1514,8 @@
 ();%0A
-  private static final String SCOPES = %22https://www.googleapis.com/auth/jobs%22;%0A
   pr
@@ -1882,16 +1882,17 @@
 s.com%22;%0A
+%0A
     Http
@@ -1930,16 +1930,47 @@
 alizer =
+%0A        request -%3E %7B%0A         
  new Htt
@@ -2000,17 +2000,187 @@
 dential)
-;
+.initialize(request);%0A          request.setConnectTimeout(60000); // 1 minute connect timeout%0A          request.setReadTimeout(60000); // 1 minute read timeout%0A        %7D;%0A
 %0A    ret
@@ -2219,21 +2219,8 @@
 der(
-%0A            
 NET_
@@ -2249,31 +2249,16 @@
 ACTORY, 
-setHttpTimeout(
 requestI
@@ -2268,17 +2268,16 @@
 ializer)
-)
 %0A       
@@ -2721,16 +2721,27 @@
 efault()
+%0A          
 .createS
@@ -2772,13 +2772,37 @@
 ton(
-SCOPE
+CloudTalentSolutionScopes.JOB
 S));
@@ -2852,16 +2852,18 @@
 ut.print
+ln
 (%22Error 
@@ -2942,410 +2942,8 @@
  %7D%0A%0A
-  private static HttpRequestInitializer setHttpTimeout(%0A      final HttpRequestInitializer requestInitializer) %7B%0A    return request -%3E %7B%0A      requestInitializer.initialize(request);%0A      request.setHeaders(new HttpHeaders().set(%22X-GFE-SSL%22, %22yes%22));%0A      request.setConnectTimeout(1 * 60000); // 1 minute connect timeout%0A      request.setReadTimeout(1 * 60000); // 1 minute read timeout%0A    %7D;%0A  %7D%0A%0A
   pu

refactor auth section of the jobs samples (#5084)