package com.axis.innovators.box.network;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;

/**
 * 网络用户管理
 * @author tzdwindows 7
 */
public class NetworkUserManagement {
    static final String BASE_URL = "https://yourdomain.com";

    /**
     * 注册用户
     * @param username 用户名
     * @param password 用户密码
     * @return 用户信息
     * @throws IOException 注册失败时抛出异常
     */
    public Users registerUser(String username, String password) throws IOException {
        long timestamp = Instant.now().getEpochSecond();
        String jsonInput = String.format(
                "{\"username\": \"%s\", \"password\": \"%s\", \"timestamp\": %d}",
                username, password, timestamp
        );

        HttpURLConnection connection = sendPostRequest("/register", jsonInput);
        return parseUserResponse(connection, username, password);
    }

    /**
     * 登录用户
     * @param username 用户名
     * @param password 用户密码
     * @return 用户信息
     * @throws IOException 登录失败时抛出异常
     */
    public Users loginUser(String username, String password) throws IOException {
        long timestamp = Instant.now().getEpochSecond();
        String jsonInput = String.format(
                "{\"username\": \"%s\", \"password\": \"%s\", \"timestamp\": %d}",
                username, password, timestamp
        );

        HttpURLConnection connection = sendPostRequest("/login", jsonInput);
        return parseUserResponse(connection, username, password);
    }

    private HttpURLConnection sendPostRequest(String endpoint, String jsonInput) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(BASE_URL + endpoint).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInput.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        return connection;
    }

    private Users parseUserResponse(HttpURLConnection connection, String username, String password) throws IOException {
        int status = connection.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_CREATED) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                String token = extractToken(response.toString());
                Users user = new Users();
                user.setUsername(username);
                user.setPassword(password);
                // 注意：实际应存储哈希值
                user.setToken(token);
                user.setTimestamp(Instant.now().getEpochSecond());
                return user;
            }
        } else {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    errorResponse.append(line);
                }
                throw new RuntimeException("Registration/Login failed: " + errorResponse);
            }
        }
    }

    private String extractToken(String jsonResponse) {
        // 简单实现，实际应使用JSON解析库
        return jsonResponse.split("\"token\":\"")[1].split("\"")[0];
    }
}