package com.secureline.server;

import android.content.Context;
import android.hardware.SensorPrivacyManager;
import android.provider.Settings;
import android.util.Slog;

final class SecureLineSensorLockdown {

    private static final String TAG = "SecureLineSensorLock";

    private static final String KEY_CAMERA =
            "secureline_camera_lockdown";

    private static final String KEY_MICROPHONE =
            "secureline_microphone_lockdown";

    private final Context mContext;
    private final SensorPrivacyManager mSensorPrivacyManager;

    SecureLineSensorLockdown(Context context) {
        mContext = context;
        mSensorPrivacyManager =
                context.getSystemService(SensorPrivacyManager.class);
    }

    void applyPersistedState() {
        setCameraLockdown(isCameraLockdownEnabled());
        setMicrophoneLockdown(isMicrophoneLockdownEnabled());
    }

    boolean isCameraLockdownEnabled() {
        return Settings.Global.getInt(
                mContext.getContentResolver(),
                KEY_CAMERA,
                0
        ) == 1;
    }

    boolean isMicrophoneLockdownEnabled() {
        return Settings.Global.getInt(
                mContext.getContentResolver(),
                KEY_MICROPHONE,
                0
        ) == 1;
    }

    void setCameraLockdown(boolean enabled) {
        Settings.Global.putInt(
                mContext.getContentResolver(),
                KEY_CAMERA,
                enabled ? 1 : 0
        );

        setSensorPrivacy(
                SensorPrivacyManager.Sensors.CAMERA,
                enabled
        );

        Slog.i(TAG, "Camera Lockdown=" + enabled);
    }

    void setMicrophoneLockdown(boolean enabled) {
        Settings.Global.putInt(
                mContext.getContentResolver(),
                KEY_MICROPHONE,
                enabled ? 1 : 0
        );

        setSensorPrivacy(
                SensorPrivacyManager.Sensors.MICROPHONE,
                enabled
        );

        Slog.i(TAG, "Microphone Lockdown=" + enabled);
    }

    private void setSensorPrivacy(
            int sensor,
            boolean enabled
    ) {
        if (mSensorPrivacyManager == null) {
            Slog.e(TAG, "SensorPrivacyManager unavailable");
            return;
        }

        try {
            mSensorPrivacyManager.setSensorPrivacy(
                    SensorPrivacyManager.Sources.OTHER,
                    sensor,
                    enabled
            );
        } catch (Throwable t) {
            Slog.e(TAG, "Failed changing sensor privacy", t);
        }
    }
}
