using System;
using System.Collections.Generic;
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.Shapes;

namespace KinoPoisk
{
    /// <summary>
    /// Логика взаимодействия для BuyTicketsWin.xaml
    /// </summary>
    public partial class BuyTicketsWin : Window
    {
        public BuyTicketsWin()
        {
            InitializeComponent();
            KinoPoiskContext context = new KinoPoiskContext();
            var films = context.MovieSessions.Where(x => x.Seats > 0 && x.DatePremiers > DateTime.Now);
            var film1 = context.Films;
            foreach (var item in films)
            {    
                Namefilm.Items.Add(item.IdFilm);
            }
            foreach (var item1 in film1)
            {
                List.Items.Add($"Фильм: {item1.NameFilm} его ИД: {item1.Id}");
            }
        }

        private void BuyTicket_Click(object sender, RoutedEventArgs e)
        {
            if (Namefilm.Text != "")
            {
                KinoPoiskContext context = new KinoPoiskContext();
                var ticket = context.Tickets;

                

                Ticket newTicket = new Ticket()
                {
                    IdFilm = Convert.ToInt32(Namefilm.Text),
                    IdOwner = UserData.Id,
                    DatePurchase = DateTime.Now,
                };

                ticket.Add(newTicket);
                context.SaveChanges();

                var movie = context.MovieSessions;

                var updMovie = movie.SingleOrDefault(x => x.IdFilm == Convert.ToInt32(Namefilm.Text) && x.DatePremiers > DateTime.Now);

                updMovie.Seats -= 1;

                movie.Update(updMovie);
                context.SaveChanges();

                MessageBox.Show($"Вы успешно купили билет!\nИд вашего билета: {newTicket.Id}\nМожете спакойно смотреть фильм!");

                MainMenu mainmenu = new MainMenu();
                this.Hide();
                mainmenu.Show();
            }
        }

        private void Cansel_Click(object sender, RoutedEventArgs e)
        {
            MainMenu mainmenu = new MainMenu();
            this.Hide();
            mainmenu.Show();
        }
    }
}
