package com.khronos.vulkan_samples;

import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class CameraDataFetcher {

    public interface CameraDataCallback {
        void onSuccess(CameraData data);
        void onError(String errorMessage);
    }

    // 数据模型类
    public static class CameraData {
        public float fov;
        public float x;
        public float y;
        public float z;
        public float sx;
        public float sy;
        public float sz;
        public float rotx;
        public float roty;
        public float rotz;
        public float camx;
        public float camy;
        public float camz;
        public float z_rate;

        // 从JSONObject解析数据
        public static CameraData fromJson(JSONObject json) {
            CameraData data = new CameraData();
            try {
                data.fov = (float) json.getDouble("fov");
                data.x = (float)json.getDouble("x");
                data.y = (float)json.getDouble("y");
                data.z = (float)json.getDouble("z");
                data.sx = (float)json.getDouble("sx");
                data.sy = (float)json.getDouble("sy");
                data.sz = (float)json.getDouble("sz");
                data.rotx = (float)json.getDouble("rotx");
                data.roty = (float)json.getDouble("roty");
                data.rotz = (float)json.getDouble("rotz");
                data.camx = (float)json.getDouble("camx");
                data.camy = (float)json.getDouble("camy");
                data.camz = (float)json.getDouble("camz");
                data.z_rate = (float)json.getDouble("z_rate");
            } catch (Exception e) {
                Log.e("CameraData", "解析JSON失败: " + e.getMessage());
            }
            return data;
        }


        @Override
        public String toString() {
            return String.format(
                    "CameraData{fov=%.2f, x=%.2f, y=%.2f, z=%.2f," +
                            "rotx=%.2f, roty=%.2f, rotz=%.2f, camx=%.2f, camy=%.2f, camz=%.2f}",
                    fov, x, y, z, rotx, roty, rotz, camx, camy, camz
            );
        }
    }

    /**
     * 异步获取相机数据
     * @param apiUrl 接口URL
     * @param callback 回调接口
     */
    public static void fetchCameraData(String apiUrl, CameraDataCallback callback) {
        new FetchCameraDataTask(callback).execute(apiUrl);
    }

    // 异步任务类
    private static class FetchCameraDataTask extends AsyncTask<String, Void, CameraData> {
        private CameraDataCallback callback;
        private String errorMessage;

        public FetchCameraDataTask(CameraDataCallback callback) {
            this.callback = callback;
        }

        @Override
        protected CameraData doInBackground(String... urls) {
            if (urls.length == 0) {
                errorMessage = "URL不能为空";
                return null;
            }

            String apiUrl = urls[0];
            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(apiUrl);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(10000); // 10秒连接超时
                connection.setReadTimeout(10000);    // 10秒读取超时
                connection.setRequestProperty("Accept", "application/json");

                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(inputStream));

                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    JSONObject jsonObject = new JSONObject(response.toString());
                    return CameraData.fromJson(jsonObject);
                } else {
                    errorMessage = "HTTP请求失败，响应码: " + responseCode;
                    return null;
                }
            } catch (Exception e) {
                errorMessage = "获取相机数据时发生错误: " + e.getMessage();
                Log.e("CameraDataFetcher", errorMessage, e);
                return null;
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (Exception e) {
                    Log.e("CameraDataFetcher", "关闭流时出错", e);
                }
            }
        }

        @Override
        protected void onPostExecute(CameraData result) {
            if (callback != null) {
                if (result != null) {
                    callback.onSuccess(result);
                } else {
                    callback.onError(errorMessage != null ? errorMessage : "未知错误");
                }
            }
        }
    }
}