package com.wytehat.btlogger;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

/**
 * Keeps the phone-sized UI readable on tablets and unfolded foldables.
 *
 * The screens are laid out for a ~360dp phone. Stretched across a 670dp+
 * inner display every row spans the full width, which leaves controls
 * marooned at opposite edges. Centering the content in a phone-width column
 * keeps the proportions the layouts were designed for.
 */
final class LargeScreenLayout {

    /** Below this the layout is already phone-shaped; leave it alone. */
    private static final int WIDE_THRESHOLD_DP = 640;

    /** Column width used once the screen is wider than the threshold. */
    private static final int CONTENT_WIDTH_DP = 600;

    private LargeScreenLayout() {
    }

    /**
     * Call after setContentView. No-op on phones and on folded screens.
     */
    static void constrain(Activity activity) {

        float density =
            activity.getResources().getDisplayMetrics().density;

        int widthDp = (int)
            (activity.getResources().getDisplayMetrics().widthPixels / density);

        if (widthDp < WIDE_THRESHOLD_DP) {
            return;
        }

        View content =
            activity.findViewById(android.R.id.content);

        if (!(content instanceof ViewGroup)) {
            return;
        }

        ViewGroup holder = (ViewGroup) content;

        if (holder.getChildCount() == 0) {
            return;
        }

        View root = holder.getChildAt(0);

        ViewGroup.LayoutParams existing =
            root.getLayoutParams();

        if (!(existing instanceof FrameLayout.LayoutParams)) {
            return;
        }

        FrameLayout.LayoutParams params =
            (FrameLayout.LayoutParams) existing;

        params.width = (int) (CONTENT_WIDTH_DP * density + 0.5f);
        params.gravity = android.view.Gravity.CENTER_HORIZONTAL;

        root.setLayoutParams(params);
    }
}
