using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using MLEM.Extensions;
using MLEM.Misc;
using TouchyTickets;
using Uri = Android.Net.Uri;

namespace Android;

[Activity(
    Label = "@string/app_name",
    MainLauncher = true,
    Icon = "@drawable/icon",
    AlwaysRetainTaskState = true,
    LaunchMode = LaunchMode.SingleInstance,
    ScreenOrientation = ScreenOrientation.UserPortrait,
    ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.Keyboard | ConfigChanges.KeyboardHidden | ConfigChanges.ScreenSize
)]
public class Activity1 : AndroidGameActivity {

    private GameImpl game;
    private AndroidPlatform platform;
    private View view;

    protected override void OnCreate(Bundle bundle) {
        base.OnCreate(bundle);

        // set up the game
        MlemPlatform.Current = new MlemPlatform.Mobile(KeyboardInput.Show, l => this.StartActivity(new Intent(Intent.ActionView, Uri.Parse(l))));
        this.platform = new AndroidPlatform(this);
        this.game = new GameImpl(this.platform);
        this.game.GraphicsDeviceManager.ResetWidthAndHeight(this.game.Window);
        this.game.GraphicsDeviceManager.IsFullScreen = true;
        this.game.OnLoadContent += game => game.InputHandler.HandleMouse = false;

        var gameView = this.game.Services.GetService(typeof(View)) as View;
        gameView.LayoutChange += (_, args) => {
            // force the game size to update when the ad size changes
            this.game.GraphicsDeviceManager.PreferredBackBufferWidth = args.Right - args.Left;
            this.game.GraphicsDeviceManager.PreferredBackBufferHeight = args.Bottom - args.Top;
            this.game.GraphicsDeviceManager.ApplyChanges();
        };

        // don't render under notches
        if (Build.VERSION.SdkInt >= BuildVersionCodes.P)
            this.Window.Attributes.LayoutInDisplayCutoutMode = LayoutInDisplayCutoutMode.Never;

        this.view = this.game.Services.GetService(typeof(View)) as View;
        this.SetContentView(this.view);

        this.game.Run();
    }

    public override void OnWindowFocusChanged(bool hasFocus) {
        base.OnWindowFocusChanged(hasFocus);
#pragma warning disable CS0618
        // hide the status bar
        if (hasFocus)
            this.Window.DecorView.SystemUiVisibility = (StatusBarVisibility) (SystemUiFlags.ImmersiveSticky | SystemUiFlags.LayoutStable | SystemUiFlags.LayoutHideNavigation | SystemUiFlags.LayoutFullscreen | SystemUiFlags.HideNavigation | SystemUiFlags.Fullscreen);
#pragma warning restore CS0618
    }

}