using InABox.Core;
using InABox.DynamicGrid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace InABox.Wpf.Dashboard.Editor;
/// <summary>
/// Interaction logic for DynamicDashboardDataEditor.xaml
/// </summary>
public partial class DynamicDashboardDataEditor : UserControl, INotifyPropertyChanged
{
    private bool _hasMultipleQueries;
    public bool HasMultipleQueries
    {
        get => _hasMultipleQueries;
        set
        {
            _hasMultipleQueries = value;
            OnPropertyChanged();
        }
    }

    public DynamicDashboardDataEditor(DynamicDashboardDataComponent data)
    {
        InitializeComponent();

        QueryGrid.Items = data.Queries.Select(x => new DynamicDashboardDataQueryEditItem(x)).ToList();
        HasMultipleQueries = QueryGrid.Items.Count > 1;

        QueryGrid.Refresh(true, true);

        if (!HasMultipleQueries)
        {
            if(QueryGrid.Items.Count == 0)
            {
                QueryGrid.Items = [new()];
            }
            QueryGrid.InitialiseEditorForm(QueryEditor, [QueryGrid.Items[0]]);
        }
    }

    private void QueryGrid_OnChanged(object sender, EventArgs e)
    {
        HasMultipleQueries = QueryGrid.Items.Count > 1;
        if (!HasMultipleQueries)
        {
            if(QueryGrid.Items.Count == 0)
            {
                QueryGrid.Items = [new()];
            }
            QueryGrid.InitialiseEditorForm(QueryEditor, [QueryGrid.Items[0]]);
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (!QueryEditor.Validate())
        {
            return;
        }

        var item = QueryGrid.CreateItem();
        if (QueryGrid.EditItems([item]))
        {
            QueryEditor.SaveItem(new CancelEventArgs());
            QueryGrid.DoChanged();
            QueryGrid.Refresh(false, true);
        }
    }

    public static bool Execute(DynamicDashboardDataComponent data)
    {
        var editor = new DynamicDashboardDataEditor(data);
        var dlg = new DynamicContentDialog(editor)
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen,
            Title = "Select Dashboard Data",
            CanSave = true
        };
        if(dlg.ShowDialog() == true)
        {
            data.Queries = editor.QueryGrid.Items.Select(x => x.ToQuery()).NotNull().ToList();
            return true;
        }
        else
        {
            return false;
        }
    }
}
