package com.warren.iwanttoheal;

import android.view.Display;
import android.view.Window;
import android.view.WindowManager;

final class AndroidDisplayPerformance {

    private static final float TARGET_REFRESH_RATE = 60.0f;

    private AndroidDisplayPerformance() {}

    static void preferBatteryRefreshRate(Window window, Display display) {
        if (window == null || display == null) return;
        Display.Mode currentMode = display.getMode();
        Display.Mode selectedMode = closestBatteryMode(display, currentMode);
        if (selectedMode == null) return;

        WindowManager.LayoutParams attributes = window.getAttributes();
        if (attributes.preferredDisplayModeId == selectedMode.getModeId()) return;
        attributes.preferredDisplayModeId = selectedMode.getModeId();
        window.setAttributes(attributes);
    }

    private static Display.Mode closestBatteryMode(Display display, Display.Mode currentMode) {
        Display.Mode selectedMode = null;
        float selectedScore = Float.MAX_VALUE;

        for (Display.Mode mode : display.getSupportedModes()) {
            if (
                currentMode != null
                    && (
                        mode.getPhysicalWidth() != currentMode.getPhysicalWidth()
                            || mode.getPhysicalHeight() != currentMode.getPhysicalHeight()
                    )
            ) {
                continue;
            }

            float refreshRate = mode.getRefreshRate();
            float score = Math.abs(refreshRate - TARGET_REFRESH_RATE);
            if (refreshRate > TARGET_REFRESH_RATE + 0.5f) score += 1000.0f;
            if (score < selectedScore) {
                selectedMode = mode;
                selectedScore = score;
            }
        }

        return selectedMode;
    }
}
