using Microsoft.Win32;
using NBAManagement.Models;
using NBAManagment.Entities;
using NBAManagment.Filter;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace NBAManagment
{
    public partial class PhotosPage : Window
    {
        private const int PAGE_ELEMENT_COUNT = 12;

        public PagedEnumerable<NBAManagement.Models.Image> PagedImage { get; private set; }
        public int PageNum
        {
            get => PagedImage.CurrentPageNum;
            set
            {
                PagedImage.CurrentPageNum = value;
                UpdateBindings();
            }
        }
        public PhotosPage()
        {
            InitializeComponent();

            using (var context = new PracticeNBAEntities()) // Создание экземпляра контекста
            {
                var images = context.Image
                    .OrderByDescending(p => p.CreateTime)
                    .ToList();

                if (images.Count == 0)
                {
                    MessageBox.Show("No images found in the database.");
                    return;
                }

                // Преобразование List<NBAManagment.Entities.Image> в List<NBAManagement.Models.Image>
                var pagedImages = images.Select(img => new NBAManagement.Models.Image
                {
                    Id = img.IdImage,
                    CreateTime = img.CreateTime ?? DateTime.MinValue,
                    ImageSource = LoadImage(img.Image1) // Загрузка изображения
                }).ToList();

                PagedImage = new PagedEnumerable<NBAManagement.Models.Image>(pagedImages, PAGE_ELEMENT_COUNT);
                DataContext = this;
            }
        }

        private BitmapImage LoadImage(byte[] imageData)
        {
            if (imageData == null || imageData.Length == 0)
            {
                MessageBox.Show("Image data is null or empty.");
                return null;
            }

            var bitmap = new BitmapImage();
            using (var mem = new MemoryStream(imageData))
            {
                mem.Position = 0;
                bitmap.BeginInit();
                bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.UriSource = null;
                bitmap.StreamSource = mem;
                bitmap.EndInit();
            }
            bitmap.Freeze();
            return bitmap;
        }

        public void UpdateBindings()
        {
            var dataContext = DataContext;
            DataContext = null;
            DataContext = dataContext;
        }

        private void FirstPage(object sender, RoutedEventArgs e)
        {
            PageNum = 1;
        }

        private void PriveusPage(object sender, RoutedEventArgs e)
        {
            PageNum--;
        }

        private void NextPage(object sender, RoutedEventArgs e)
        {
            PageNum++;
        }

        private void LastPage(object sender, RoutedEventArgs e)
        {
            PageNum = PagedImage.PageCount;
        }

        private NBAManagement.Models.Image pictureToDownload;
        private void DownloadImage(object sender, RoutedEventArgs e)
        {
            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Png | *.png";
            downloadPoput.IsOpen = false;
            if (saveFileDialog.ShowDialog() != true)
                return;

            if (!Directory.Exists(System.IO.Path.GetDirectoryName(saveFileDialog.FileName)))
            {
                MessageBox.Show("Путь несуществует", "Ошибка",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            pictureToDownload.SaveAsFile(saveFileDialog.FileName);
        }

        private void DownloadPageImages(object sender, RoutedEventArgs e)
        {
            var folderDialog = new System.Windows.Forms.FolderBrowserDialog();
            if (folderDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;

            int i = 0;
            foreach (var item in PagedImage.CurrentPage)
            {
                item.SaveAsFile($@"{folderDialog.SelectedPath}/picture{++i}.png");
            }

            MessageBox.Show("Файлы успешно записаны на диск");
        }

        private void ShowDownloadPoput(object sender, MouseButtonEventArgs e)
        {
            pictureToDownload = (NBAManagement.Models.Image)((Button)sender).DataContext;
            downloadPoput.IsOpen = true;
        }
    }
}
