package com.ads.cal.calculator.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.ads.cal.calculator.R;
import com.ads.cal.calculator.base.BaseActivity;
import com.ads.cal.calculator.utils.EventIdUtils;
import com.ads.cal.calculator.utils.FireBaseAnalyticsUtils;
import com.ads.cal.calculator.utils.LocationMgr;
import com.ads.cal.calculator.utils.SensorUtils;

import java.text.DecimalFormat;

public class CompassActivity extends BaseActivity {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 123; // 自定义的请求码
    private LocationMgr locationMgr;

    @Override
    protected String getPageExpEventId() {
        return EventIdUtils.COMPASS_EXP;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.app_activity_compass;
    }

    private ImageView compass, compress_direction;
    private TextView degrees;
    private TextView lat, latTextView, lot, lotTextView;


    private SensorEventListener sensorEventListener;
    private SensorManager sensorManager;
    private Sensor accelerometer, magnetometer;

    private double lastDegrees;
    private double currentDegrees;
    private long lastUpdateTime = 0;
    private static final float ALPHA = 0.9f; // 调整这个值以控制平滑程度


    @Override
    protected void initView() {
        compass = findViewById(R.id.compress);
        compress_direction = findViewById(R.id.compress_direction);
        degrees = findViewById(R.id.degrees);
        lat = findViewById(R.id.lat);
        latTextView = findViewById(R.id.lat_text);
        lot = findViewById(R.id.lot);
        lotTextView = findViewById(R.id.lot_text);
    }

    @Override
    protected void initData() {
        initSensorManager();

        // 初始化LocationMgr，传递一个LocationCallback
        locationMgr = new LocationMgr((latitude, longitude) -> {
            // 在此处处理获取到的位置数据
            if (latitude.length > 1) {
                lat.setText(latitude[1]);
            }
            if (latitude.length > 0) {
                latTextView.setText(latitude[0]);
            }
            if (longitude.length > 1) {
                lot.setText(longitude[1]);
            }
            if (longitude.length > 0) {
                lotTextView.setText(longitude[0]);
            }
        });

        // 检查定位权限
        if (checkLocationPermission()) {
            // 如果已经有定位权限，可以开始定位
            locationMgr.startLocation();
        } else {
            // 如果没有定位权限，请求权限
            requestLocationPermission();
        }
    }

    private void initSensorManager() {
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        // 检查传感器是否可用
        if (accelerometer != null && magnetometer != null) {
            if (null == sensorEventListener) {
                // 创建传感器监听器
                sensorEventListener = new SensorEventListener() {
                    final float[] accelerometerData = new float[3];
                    final float[] magnetometerData = new float[3];

                    @Override
                    public void onSensorChanged(SensorEvent event) {
                        if (event.sensor == accelerometer) {
                            // 平滑加速度计数据
                            for (int i = 0; i < event.values.length; i++) {
                                accelerometerData[i] = ALPHA * accelerometerData[i] + (1 - ALPHA) * event.values[i];
                            }
                        } else if (event.sensor == magnetometer) {
                            // 平滑磁力计数据
                            for (int i = 0; i < event.values.length; i++) {
                                magnetometerData[i] = ALPHA * magnetometerData[i] + (1 - ALPHA) * event.values[i];
                            }
                        }
                        // 只在两个传感器都有数据时计算方向并更新指南针
                        updateCompass(accelerometerData, magnetometerData);
                    }

                    @Override
                    public void onAccuracyChanged(Sensor sensor, int accuracy) {
                        // 传感器精度改变时的处理
                    }
                };
            }

        } else {
            // 加速度计或磁力计不可用，进行错误处理
        }
    }

    private void updateCompass(float[] accelerometerData, float[] magnetometerData) {
        // 计算方向并更新指南针
        float[] rotationMatrix = new float[9];
        float[] orientationValues = new float[3];
        boolean success = SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerData, magnetometerData);
        if (success) {
            SensorManager.getOrientation(rotationMatrix, orientationValues);
            // 获取当前时间
            long currentTime = System.currentTimeMillis();
            // 更新指南针或其他UI元素
            currentDegrees = Math.toDegrees(orientationValues[0]);

            if (Math.abs(currentDegrees - lastDegrees) >= 1 && currentTime - lastUpdateTime >= 20) {
                Log.e("AAAAA", "   " + "degree   " + currentDegrees);
                runOnUiThread(runnable);
                lastUpdateTime = currentTime;
                // 更新上次更新时间
            }
        }
    }

    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            rotate(currentDegrees);
        }
    };

    private void rotate(double currentDegrees) {
        double rotation = (currentDegrees + 360) % 360;
        compass.setRotation(-(float) rotation);
        compress_direction.setRotation(-(float) rotation);
        lastDegrees = currentDegrees;
        degrees.setText(String.format("%s%s", SensorUtils.getDirectionFromAngle(currentDegrees), (int)rotation));
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 注册传感器监听器
        if (null != accelerometer) {
            sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_GAME);
        }
        if (null != magnetometer) {
            sensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_GAME);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != sensorEventListener) {
            if (null != sensorManager) {
                sensorManager.unregisterListener(sensorEventListener);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != sensorEventListener) {
            if (null != sensorManager) {
                sensorManager.unregisterListener(sensorEventListener);
                sensorEventListener = null;
            }
        }
    }

    private boolean checkLocationPermission() {
        // 检查是否有定位权限
        return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }

    private void requestLocationPermission() {
        // 请求定位权限
        ActivityCompat.requestPermissions(
                this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                LOCATION_PERMISSION_REQUEST_CODE
        );
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了定位权限，现在可以开始定位
                locationMgr.startLocation();
            } else {
                // 用户拒绝了定位权限
                FireBaseAnalyticsUtils.init().send(EventIdUtils.COMPASS_LOCATION_CANCEL);
            }
        }
    }


    public static void instance(Context context) {
        Intent intent = new Intent(context, CompassActivity.class);
        context.startActivity(intent);
    }
}
