namespace ex_ResponsivePage;

using Microsoft.Maui.Devices;
using Microsoft.Maui.Controls;

public sealed class IdiomAndOrientationStateTrigger : StateTriggerBase
{
    public IdiomAndOrientationStateTrigger()
    {
        UpdateState();
    }

    public static readonly BindableProperty IdiomProperty = 
        BindableProperty.Create("Idiom", typeof(string), typeof(IdiomAndOrientationStateTrigger), "phone");

    public string Idiom
    {
        get => GetValue(IdiomProperty) as string;
        set => SetValue(IdiomProperty, value);
    } 

    public DisplayOrientation Orientation
    {
        get => (DisplayOrientation)GetValue(OrientationProperty);
        set => SetValue(OrientationProperty, value);
    }

    public static readonly BindableProperty OrientationProperty =
        BindableProperty.Create(nameof(Orientation), typeof(DisplayOrientation), typeof(IdiomAndOrientationStateTrigger), null);

    protected override void OnAttached()
    {
        base.OnAttached();

        UpdateState();
        DeviceDisplay.MainDisplayInfoChanged += OnInfoPropertyChanged;
    }

    protected override void OnDetached()
    {
        base.OnDetached();

        DeviceDisplay.MainDisplayInfoChanged -= OnInfoPropertyChanged;
    }

    void OnInfoPropertyChanged(object? sender, DisplayInfoChangedEventArgs e) =>
			UpdateState();

    void UpdateState()
    {
        if (string.IsNullOrEmpty(Idiom))
            return;

        var idiom = DeviceIdiom.Create(Idiom);

        var currentOrientation = DeviceDisplay.MainDisplayInfo.Orientation;

        if(currentOrientation == Orientation || Orientation == DisplayOrientation.Unknown)
        {
            SetActive(DeviceInfo.Current.Idiom == idiom);
        }
        else
        {
            SetActive(false);
        }
    }
}

