package com.crm.rely.backend.util;


import com.alibaba.fastjson.JSON;
import com.crm.rely.backend.core.pojo.table.UserGoogleEmailTable;
import com.crm.rely.backend.exception.ServiceException;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;

/**
 * @Author houn
 * @Date 2025/2/20 17:30
 * @PackageName:com.crm.manager
 * @ClassName: GoogleAdminAPIHttp
 * @Description: TODO
 */
@Slf4j
public class GoogleAdminAPIHttp {
    private static final String ADMIN_DIRECTORY_USER_API_URL = "https://admin.googleapis" +
            ".com/admin/directory/v1/users";
    private static final String TOKEN_URL = "https://oauth2.googleapis.com/token";
    private static final String SCOPE = String.join(" ",
            "https://www.googleapis.com/auth/admin.directory.user",
            "https://www.googleapis.com/auth/admin.directory.group"
    );

    public static String getAccessToken(String adminEmail, String serviceAccountJson) throws Exception {

        if (Strings.isNullOrEmpty(adminEmail) || Strings.isNullOrEmpty(serviceAccountJson)) {
            throw ServiceException.exception("admin email or service account json is null");
        }
        // 解析 JSON 文件
        Map<String, Object> jsonMap = JSON.parseObject(serviceAccountJson, Map.class);

        String clientEmail = (String) jsonMap.get("client_email");
        String privateKeyPem = (String) jsonMap.get("private_key");

        // 解析私钥
        privateKeyPem = privateKeyPem.replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s", "");

        return getAccessToken(adminEmail, clientEmail, privateKeyPem);
    }

    public static String getAccessToken(String adminEmail, String clientEmail, String privateKeyPemString) throws Exception {
        if (Strings.isNullOrEmpty(adminEmail) || Strings.isNullOrEmpty(clientEmail) || Strings.isNullOrEmpty(privateKeyPemString)) {
            throw ServiceException.exception("admin email or clientEmail or privateKeyPem is null");
        }
        // 解析私钥
        String privateKeyPem = privateKeyPemString.replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s", "");

        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyPem);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));

        // 生成 JWT Header
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "RS256");
        header.put("typ", "JWT");

        // 生成 JWT Payload
        long now = System.currentTimeMillis() / 1000;
        Map<String, Object> payload = new HashMap<>();
        payload.put("iss", clientEmail);
        payload.put("sub", adminEmail); // 委派管理权限
        payload.put("scope", SCOPE);
        payload.put("aud", TOKEN_URL);
        payload.put("exp", now + 3600);
        payload.put("iat", now);

        // Base64 编码 Header 和 Payload
        String encodedHeader =
                Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.toJSONBytes(header));
        String encodedPayload =
                Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.toJSONBytes(payload));

        // 签名
        String message = encodedHeader + "." + encodedPayload;
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign((PrivateKey) privateKey);
        signature.update(message.getBytes(StandardCharsets.UTF_8));
        String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());

        String jwt = message + "." + encodedSignature;

        // 发送 HTTP POST 请求获取 Access Token
        URL url = new URL(TOKEN_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);

        String requestBody = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + jwt;
        try (OutputStream os = conn.getOutputStream()) {
            os.write(requestBody.getBytes(StandardCharsets.UTF_8));
        }

        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            String responseBody = getResponseBody(conn);
            Map<String, Object> response = JSON.parseObject(responseBody, Map.class);
            return (String) response.get("access_token");
        } else {
            return "Error: " + responseCode + " - " + getErrorResponse(conn);
        }
    }

    public static Integer createUser(String accessToken, String email, String firstName, String lastName,
                                     String password, String extraPhone, String extraEmail) throws Exception {
        validToken(accessToken);
        String urlString = ADMIN_DIRECTORY_USER_API_URL;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);


        // 1️⃣ 构造用户 JSON 数据
        Map<String, Object> userMap = new HashMap<>();
        Map<String, String> nameMap = new HashMap<>();
        nameMap.put("givenName", firstName);
        nameMap.put("familyName", lastName);
        userMap.put("name", nameMap);
        userMap.put("password", password);
        userMap.put("primaryEmail", email);

        // 2️⃣ 添加额外的电话和邮箱
        if (extraPhone != null && !extraPhone.isEmpty()) {
            Map<String, String> phoneMap = new HashMap<>();
            phoneMap.put("type", "work");
            phoneMap.put("value", extraPhone);
            userMap.put("phones", new Map[]{phoneMap});
        }

        if (extraEmail != null && !extraEmail.isEmpty()) {
            Map<String, String> emailMap = new HashMap<>();
            emailMap.put("address", extraEmail);
            emailMap.put("type", "work");
            userMap.put("emails", new Map[]{emailMap});
        }

        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = JSON.toJSONString(userMap).getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            log.info("User create successfully!");
        } else {
            log.info("User create Error: " + responseCode + " - " + getErrorResponse(conn));
        }
        return responseCode;
    }

    public static Integer deleteUser(String accessToken, String userEmail) throws Exception {
        validToken(accessToken);
        String urlString = ADMIN_DIRECTORY_USER_API_URL + "/" + userEmail;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("DELETE");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);

        int responseCode = conn.getResponseCode();
        if (responseCode == 204) {
            log.info("User deleted successfully!");
        } else {
            log.info("User deleted Error: " + responseCode + " - " + getErrorResponse(conn));
        }
        return responseCode;
    }

    /**
     * @param accessToken
     * @param userEmail
     * @return {  "kind": "admin#directory#user",  "id": "112207665165230017342",  "etag":
     * "\"CmwXoj9NwmeYWUSny9qYPKAHjB8pLfe5jMuk_1lM7Aw/PFha8YbuHDbkCYrZxK3ifyBd35s\"",  "primaryEmail": "john.doe
     * .test@cwgmarkets.com",  "name": {    "givenName": "New",    "familyName": "User2",    "fullName": "New User2"
     * },  "isAdmin": false,  "isDelegatedAdmin": false,  "lastLoginTime": "1970-01-01T00:00:00.000Z",
     * "creationTime": "2025-02-21T08:13:45.000Z",  "agreedToTerms": false,  "suspended": false,  "archived": false,
     * "changePasswordAtNextLogin": false,  "ipWhitelisted": false,  "emails": [    {      "address": "john.doe
     * .test@gmail.com",      "type": "work"    },    {      "address": "john.doe.test@cwgmarkets.com",
     * "primary": true    },    {      "address": "john.doe.test@cwgmarkets.com.test-google-a.com"    }  ],
     * "phones": [    {      "value": "123123123",      "type": "work"    }  ],  "languages": [    {
     * "languageCode": "en-GB",      "preference": "preferred"    }  ],  "nonEditableAliases": [    "john.doe
     * .test@cwgmarkets.com.test-google-a.com"  ],  "customerId": "C03fblpx8",  "orgUnitPath": "/",
     * "isMailboxSetup": true,  "isEnrolledIn2Sv": false,  "isEnforcedIn2Sv": false,  "includeInGlobalAddressList":
     * true}
     * @throws Exception
     */
    public static String getUser(String accessToken, String userEmail) throws Exception {
        validToken(accessToken);
        String urlString = ADMIN_DIRECTORY_USER_API_URL + "/" + userEmail;
        URL url = new URL(urlString);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);
        conn.setRequestProperty("Accept", "application/json;charset=UTF-8");

        int responseCode = conn.getResponseCode();

        if (responseCode == 200) {
            String responseBody = getResponseBody(conn);
            log.info("User updated successfully!\n" + responseBody);
            return responseBody;
        } else {
            log.info("Error: " + responseCode + " - " + getErrorResponse(conn));
            return null;
        }
    }

    public static Integer updateUser(String accessToken, String userEmail, String firstName, String lastName,
                                    String extraPhone, String extraEmail) throws Exception {
        validToken(accessToken);
        String urlString = ADMIN_DIRECTORY_USER_API_URL + "/" + userEmail;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        // 构造 JSON 数据
        if (Strings.isNullOrEmpty(userEmail)) {
            throw ServiceException.exception("User email is null or empty");
        }

        Map<String, Object> userMap = new HashMap<>();
        if (!Strings.isNullOrEmpty(firstName) || !Strings.isNullOrEmpty(lastName)) {
            Map<String, String> nameMap = new HashMap<>();
            nameMap.put("givenName", firstName);
            nameMap.put("familyName", lastName);
            userMap.put("name", nameMap);
        }

        List<Map<String, String>> phones = new ArrayList<>();
        if (!Strings.isNullOrEmpty(extraPhone)) {
            Map<String, String> phoneMap = new HashMap<>();
            phoneMap.put("type", "work");
            phoneMap.put("value", extraPhone);
            phones.add(phoneMap);
        }
        if (!phones.isEmpty()) {
            userMap.put("phones", phones);
        }

        List<Map<String, String>> emails = new ArrayList<>();
        if (!Strings.isNullOrEmpty(extraEmail)) {
            Map<String, String> emailMap = new HashMap<>();
            emailMap.put("address", extraEmail);
            emailMap.put("type", "work");
            emails.add(emailMap);
        }
        if (!emails.isEmpty()) {
            userMap.put("emails", emails);
        }
        conn.getOutputStream().write(JSON.toJSONString(userMap).getBytes("UTF-8"));

        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            log.info("User updated successfully!");
        } else {
            log.info("User updated Error: " + responseCode + " - " + getErrorResponse(conn));
        }
        return responseCode;

    }

    public static String renameUser(String accessToken, String oldEmail, String newEmail) throws Exception {
        validToken(accessToken);

        if (Strings.isNullOrEmpty(oldEmail) || Strings.isNullOrEmpty(newEmail)) {
            throw ServiceException.exception("Old or new email is null or empty");
        }

        // API 地址
        String urlString = ADMIN_DIRECTORY_USER_API_URL + "/" + oldEmail;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // PATCH 方法比 PUT 更安全（只更新传入字段）
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        // 构造请求体
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("primaryEmail", newEmail);

        // 写入请求数据
        conn.getOutputStream().write(JSON.toJSONString(userMap).getBytes("UTF-8"));

        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            return "User renamed successfully!\n" + getResponseBody(conn);
        } else {
            return "Error: " + responseCode + " - " + getErrorResponse(conn);
        }
    }

    public static Integer resetUserPassword(String accessToken, String userEmail, String newPassword) throws Exception {
        log.info("accessToken:" + accessToken + ",userEmail:" + userEmail);
        validToken(accessToken);
        String urlString = ADMIN_DIRECTORY_USER_API_URL + "/" + userEmail;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        // 构造 JSON 数据
        String jsonPayload = "{ \"password\": \"" + newPassword + "\" }";

        conn.getOutputStream().write(jsonPayload.getBytes("UTF-8"));

        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            log.info("User password reset successfully!");
        } else {
            log.info("User password reset Error: " + responseCode + " - " + getErrorResponse(conn));
        }
        return responseCode;

    }

    /**
     * 将用户添加到 Google 群组
     *
     * @param accessToken OAuth2 访问令牌
     * @param groupEmail  群组邮箱，例如 team@cwgmarkets.com
     * @param userEmail   要添加的用户邮箱，例如 john.doe@cwgmarkets.com
     * @param role        在群组里的角色，可选 MEMBER / MANAGER / OWNER
     */
    public static Integer addUserToGroup(String accessToken, String groupEmail, String userEmail, String role) throws Exception {
        validToken(accessToken);

        if (Strings.isNullOrEmpty(groupEmail) || Strings.isNullOrEmpty(userEmail)) {
            throw ServiceException.exception("groupEmail or userEmail is null");
        }
        if (Strings.isNullOrEmpty(role)) {
            role = "MEMBER"; // 默认成员
        }

        String urlString = "https://admin.googleapis.com/admin/directory/v1/groups/" + groupEmail + "/members";
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        Map<String, String> memberData = new HashMap<>();
        memberData.put("email", userEmail);
        memberData.put("role", role);

        try (OutputStream os = conn.getOutputStream()) {
            os.write(JSON.toJSONString(memberData).getBytes(StandardCharsets.UTF_8));
        }

        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            log.info("✅ User added to group successfully!");
        } else {
            if (responseCode == 409) {
                return 200;
            }
            log.error("❌ Error adding user to group: " + responseCode + " - " + getErrorResponse(conn));
        }
        return responseCode;
    }

    public static List<Map<String, Object>> listUsers(String accessToken) throws Exception {
        return listUsers(accessToken, "");
    }

    public static List<Map<String, Object>> listUsers(String accessToken, String customerId) throws Exception {
        validToken(accessToken);

        if (Strings.isNullOrEmpty(customerId)) {
            customerId = "my_customer"; // 默认获取整个 Workspace 下的用户
        }

        String urlString = ADMIN_DIRECTORY_USER_API_URL
                + "?customer=" + customerId
                + "&maxResults=500&orderBy=email";

        List<Map<String, Object>> users = new ArrayList<>();
        String nextPageToken = null;

        do {
            String requestUrl = urlString;
            if (nextPageToken != null) {
                requestUrl += "&pageToken=" + nextPageToken;
            }

            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "Bearer " + accessToken);
            conn.setRequestProperty("Accept", "application/json;charset=UTF-8");

            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                String responseBody = getResponseBody(conn);
                Map<String, Object> response = JSON.parseObject(responseBody, Map.class);

                // 提取用户信息
                List<Map<String, Object>> items = (List<Map<String, Object>>) response.get("users");
                if (items != null) {
                    users.addAll(items);
                }

                // 检查是否有下一页
                nextPageToken = (String) response.get("nextPageToken");
            } else {
                throw new RuntimeException("Error: " + responseCode + " - " + getErrorResponse(conn));
            }
        } while (nextPageToken != null);

        return users;
    }

    /**
     * 从 Google 群组移除用户
     *
     * @param accessToken OAuth2 访问令牌
     * @param groupEmail  群组邮箱，例如 team@cwgmarkets.com
     * @param userEmail   要移除的用户邮箱，例如 john.doe@cwgmarkets.com
     */
    public static Integer removeUserFromGroup(String accessToken, String groupEmail, String userEmail) throws Exception {
        validToken(accessToken);

        if (Strings.isNullOrEmpty(groupEmail) || Strings.isNullOrEmpty(userEmail)) {
            throw ServiceException.exception("groupEmail or userEmail is null");
        }

        String urlString = "https://admin.googleapis.com/admin/directory/v1/groups/"
                + groupEmail + "/members/" + userEmail;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("DELETE");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);

        int responseCode = conn.getResponseCode();
        if (responseCode == 204) { // 删除成功返回 204 No Content
            log.info("✅ User removed from group successfully!");
        } else {
            log.error("❌ Error removing user from group: " + responseCode + " - " + getErrorResponse(conn));
        }
        return responseCode;
    }

    private static String getResponseBody(HttpURLConnection conn) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }

    private static String getErrorResponse(HttpURLConnection conn) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }

    private static void validToken(String token) throws Exception {
        if (Strings.isNullOrEmpty(token)) {
            throw ServiceException.exception("token is null");
        }
    }

    public static void main(String[] args) throws Exception {

        String jaon = "{\n" +
                "  \"type\": \"service_account\",\n" +
                "  \"project_id\": \"manageruser-451509\",\n" +
                "  \"private_key_id\": \"e61cbc61eec9e7f81d0fa8d3312997e90c3598ec\",\n" +
                "  \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+Mpn6cD1Ln0tg\\nM4oALgRA31lAVKyq9In41Bp1oR/2rzCZXj8ZVp0D/AwHp0P9PybqvlE4wyFcJrII\\nnfxivZnEwfA76gVGFHYz8Ulp5vgJX5xNJ4poNJB5Zp9FfL//2czZGHo8sFDahTOJ\\nILHOOAwjtiL6ya826LpE+S2cyRtHWXugfZ02K9W7SphN8BZfTTdeXmT+C265EIQw\\nBQ3Q4QPwjnxzlO0EEZLr25Qz9XiPJoUFpChHU3ByRBinoz3tb53hSwNQ271Dg23u\\np/RRUE6NL/1uZtOGaFAtmkt+9SPSDI+iAhO0fn7D2D5D0FWR/TQuCgI0Vw3OZLnj\\nhuKRy1I7AgMBAAECggEAFCya35EbN1PAs4YT+7vl0JnARk4U+JcysVWSLur10H05\\nqvLvv3jL89m+zusDj6+sqZahV+N+vN8P4FEdrb2Nu2yU1k4W3B2cghr0XgrVQW1G\\nT3rDuBTnRDFJ8J1wYiuQinCJurk7AkrBsihpI8YXJ4yQvkg5URozc9B4cZp1TcZ1\\nkk1pHg/NoIVRMG8Iwi4W/hmZDzgSQMTM55hupNkx5EH7On7VR4cFJ+/ViTZwlPAp\\n3B7mQ1oj91WEWrE2t1mlTpfmg6y7i9nzoA1ox4uUPJl8eWeufSpInT3sm5uw7+jx\\n6ximBuO6dL1237EONKIunPP5GTSeCWvCIS7vmkgzOQKBgQDxUhm8+6HqGWY/Yf3G\\nPLlpD/7SxxlbCuFKzsvKYQDBWau5xj3A2pQPjU/trZ8jnJD8CziigAh4mYx5/cQZ\\n3LjG8CF0/lzuOwowK8oNOvMuEoaKhEQudky5h+EHnHw4FCcMyOvDBQKt6oYigThF\\nlpw4ueyvaGyGO7uOjwND8zK74wKBgQDJxGbOerGOq4+evFJQFyFAHJlPMm32aL74\\nZzISzBPKQqGYqKlJIZ3lOBlSx4VsFEV7RKvYL+b9nGClmQCoDKZkCMdovOpCs8p7\\nR6TPK5AMMxTLsGdnZwbhsvFpr5qUJWIxoB0txcEcWDWsky6v24vgSftUoZzj5U6l\\nzJD+25aPyQKBgFtzhZV8tsuEfJ8gf4+Ui58pFKTEFvPNl7tFyy0SvbqIRO/OFLD1\\nJI8QOm4UEe7o8njRt9C9PHiXmAjTBnHWl5+seMFhc85ESYQf1B5XbLjVBG+R2FTT\\nOBhHShwcTWbjHDlYGyB40Z8e9V42IiEdBm7o5q1CoX3tPRK1V8N0cpGJAoGBAKF3\\noop1F+lEFKCEtx7PE9X5zRrbEbMTaljiROlUFjZUEnxX5XnYBEMvHNzpPTYcFuqq\\nLxfIZgPphFKh2iuiS/pcKDECljqhJVZ5JESC6TlKG8dSOb4/bftrN9VLKdqK/EUY\\njKFX0836LaIY+1DS0uLAcfjtiN+8X69BwXujgZ85AoGAFOXNwAA4pJwfh4tjMdCH\\nvBR/BDCp7kLu1+XZeSkwxpb4fqBhqtSaGPsHMs1VjZfuTJ+W64hdqPXwLmKQ8yvV\\n8zzvxkgh87rDNIjNUXaKntTEQkSbhR90w6JRstUM0EdpxsXy3Ml00dOeeBb0WtdB\\nzh0XoW/f0Xsa+Ygst/n5uSw=\\n-----END PRIVATE KEY-----\\n\",\n" +
                "  \"client_email\": \"manageruser@manageruser-451509.iam.gserviceaccount.com\",\n" +
                "  \"client_id\": \"108768971673921067265\",\n" +
                "  \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n" +
                "  \"token_uri\": \"https://oauth2.googleapis.com/token\",\n" +
                "  \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n" +
                "  \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/manageruser%40manageruser-451509.iam.gserviceaccount.com\",\n" +
                "  \"universe_domain\": \"googleapis.com\",\n" +
                "  \"admin_email\": \"landon@cwgmarkets.com\"\n" +
                "}";
        String adminEmail = "landon@cwgmarkets.com";
        String accessToken = getAccessToken(adminEmail, jaon);
        System.out.println(accessToken);

        String firstName = "NG";
        String lastName = "SOOK HUEYT";
        String password = GetRandom.getRandomPasswordString();
        System.out.println(password);
        String extraEmail = "1640ww23@163.com";
        String extraPhone = "011-133 221346";

        String userEmail = "yxcd@cwgmarkets.com";

        System.out.println("userEmail:" + userEmail);
        System.out.println("password:" + password);
        List<Map<String, Object>> maps = listUsers(accessToken, "");
        System.out.println(maps);

//        String content = "Roy.S@cwgmarkets.com,Roy.Shen@cwgmarkets.com\n" +
//                "Jony.Y@cwgmarkets.com,Jony.Yang@cwgmarkets.com\n" +
//                "Shawn.Y@cwgmarkets.com,Shawn.Yang@cwgmarkets.com\n" +
//                "kimi.s@cwgmarkets.com,Kimi.Shi@cwgmarkets.com\n" +
//                "Selina.He@cwgmarkets.com,Selina.He@cwgmarkets.com\n" +
//                "Mike.z@cwgmarkets.com,Mike.Zhang@cwgmarkets.com\n" +
//                "Lucky.Zhang@cwgmarkets.com,Lucky.Zhang@cwgmarkets.com\n" +
//                "Sean.Yang@cwgmarkets.com,Sean.Yang@cwgmarkets.com\n" +
//                "Gavin.Guo@cwgmarkets.com,Gavin.Guo@cwgmarkets.com\n" +
//                "Sunny.Z@cwgmarkets.com,Sunny.Zhou@cwgmarkets.com";
//        String[] renameUsers = content.split("\n");
//        if (renameUsers.length <= 0) {
//            return;
//        }
//        for (String renameUser : renameUsers) {
//            String[] rename = renameUser.split(",");
//            if (rename.length < 2) {
//                break;
//            }
//
//            System.out.println(rename[0] + "--" + rename[1]);
//            renameUser(accessToken, rename[0], rename[1]);
//        }
//        System.out.println(getUser(accessToken, "kevin.chen@cwgmarkets.com"));

//        addUserToGroup(accessToken, "abuse@cwgmarkets.com", "landon@cwgmarkets.com", "MEMBER");
// test.f.l@cwgmarkets.com
//        System.out.println("User Info: \n" + deleteUser(accessToken, "john.doe.test@cwgmarkets.com"));
//        System.out.println("User Info: \n" + createUser(accessToken, userEmail, firstName, lastName, password,
//                extraPhone, extraEmail));
//        System.out.println("User Info: \n" + deleteUser(accessToken, userEmail));
//        String userEmail = "landon@cwgmarkets.com";
//        getUser(accessToken, userEmail);
//        System.out.println("User Info: \n" + userInfo);
//        System.out.println("User Info: \n" + createUser(accessToken, userEmail, firstName, lastName, password,
//                extraPhone, extraEmail));
//        System.out.println("User Info: \n" + updateUser(accessToken, userEmail, firstName, lastName, extraPhone,
//                extraEmail));
//        System.out.println("User Info: \n" + resetUserPassword(accessToken, userEmail, password));

//        String userEmail = "john.doe.test@cwgmarkets.com";
//        System.out.println("User Info: \n" + getUser(accessToken, userEmail));
//        System.out.println("User Info: \n" + updateUser(accessToken, userEmail, "New", "User2"));
//        System.out.println("User Info: \n" + resetUserPassword(accessToken, userEmail, "Secur@#ePass123!"));
//        System.out.println("User Info: \n" + deleteUser(accessToken, userEmail));
//
//        createUser(accessToken, "john.doe.test@cwgmarkets.com", "New", "User", "Secur@#ePass123!");
    }
}