using System;
using System.Collections.Generic;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using ComputerShopWpf.Services;
using Npgsql;

namespace ComputerShopWpf.Views
{
    public partial class OrderItemsPage : Page
    {
        private readonly DatabaseService _database = new DatabaseService();
        private readonly int _orderId;

        public OrderItemsPage(int orderId, string orderInfo)
        {
            InitializeComponent();
            _orderId = orderId;
            OrderInfoTextBlock.Text = orderInfo;
            LoadOrderItems();
        }

        private void LoadOrderItems()
        {
            try
            {
                DataTable table = _database.ExecuteSelect(
                    "SELECT * FROM v_order_items_full WHERE order_id = @order_id ORDER BY product_name;",
                    new Dictionary<string, object> { { "@order_id", _orderId } });
                OrderItemsDataGrid.ItemsSource = table.DefaultView;
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            if (NavigationService != null && NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
        }

        private static void ShowDatabaseError(Exception ex)
        {
            PostgresException postgresException = ex as PostgresException;
            if (postgresException != null)
            {
                MessageBox.Show("Ошибка PostgreSQL: " + postgresException.MessageText, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            NpgsqlException npgsqlException = ex as NpgsqlException;
            if (npgsqlException != null)
            {
                MessageBox.Show("Ошибка подключения к базе данных: " + npgsqlException.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            MessageBox.Show("Ошибка: " + ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }
}
