using Elwig.Helpers;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

namespace Elwig.Windows {
    public partial class QueryWindow : Window {

        private ICommand? _enterCommand;
        public ICommand EnterCommand => _enterCommand ??= new ActionCommand(async () => {
            await ExecuteQuery();
        });


        public QueryWindow() {
            InitializeComponent();
        }

        private async void QueryButton_Click(object sender, RoutedEventArgs evt) {
            await ExecuteQuery();
        }

        private async Task ExecuteQuery() {
            try {
                await ExecuteQuery(QueryInput.Text);
            } catch (Exception e) {
                MessageBox.Show(e.Message, "Fehler beim Ausführen", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task ExecuteQuery(string sqlQuery) {
            var rows = new List<object[]>();
            IList<DbColumn> header;

            using (var cnx = await AppDbContext.ConnectAsync()) {
                var cmd = cnx.CreateCommand();
                cmd.CommandText = sqlQuery;
                using var reader = await cmd.ExecuteReaderAsync();
                header = await reader.GetColumnSchemaAsync();
                while (await reader.ReadAsync()) {
                    var values = new object[reader.FieldCount];
                    reader.GetValues(values);
                    rows.Add(values);
                }
            }

            var styleRight = new Style();
            styleRight.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));

            DataList.Columns.Clear();
            for (int i = 0; i < header.Count; i++) {
                var h = header[i];
                DataList.Columns.Add(new DataGridTextColumn {
                    Header = h.ColumnName.Replace("_", "__"),
                    Binding = new Binding($"[{i}]"),
                    CellStyle = (h.DataTypeName == "INTEGER" || h.DataTypeName == "REAL") ? styleRight : null,
                });
            }
            DataList.ItemsSource = rows;
        }
    }
}
