package com.ruoyi.common.spider.reptile;
import cn.hutool.json.JSONObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author vmlogin
*       <dependency>
*          <groupId> org.seleniumhq.selenium <groupId/>
*          <artifactId> selenium-java <artifactId/>
*          <version> 3.141.59 <version/>
*       <dependency>
*/
public class ProductChrome {
     public static void main (String[] args) throws Exception {
         ProductChrome pc = new ProductChrome();
         String profileId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
         //Open and get the remote debugging address according to the profileId
         URL url = new URL(pc.startProfile(profileId));
         //Use the remote debugging address to connect the opened chrome browser
         ChromeOptions chromeOptions = new ChromeOptions();
         chromeOptions.setExperimentalOption("debuggerAddress", url.getAuthority());
         WebDriver driver = new ChromeDriver(chromeOptions);
         //visit vmlogin
         driver.get("https://www.vmlogin.us/");
         System.out.println(driver.getTitle());
         driver.quit();
     }
     private String startProfile(String profileId) throws Exception {
         String url = "http://127.0.0.1:35000/api/v1/profile/start?automation=true&profileId=" + profileId;
         URL obj = new URL(url);
         HttpURLConnection con = (HttpURLConnection) obj.openConnection();
         con.setRequestMethod("GET");
         BufferedReader in = new BufferedReader(
                 new InputStreamReader(con.getInputStream()));
         String inputLine;
         StringBuffer response = new StringBuffer();
         while ((inputLine = in.readLine()) != null) {
             response.append(inputLine);
         in.close();
         JSONObject jsonResponse = new JSONObject(response.toString());
         return jsonResponse.getStr("value");
     }
}