using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelAgencyWindow.Data;
using System.Windows.Input;
using System.Windows;

namespace TravelAgencyWindow.Model.ListModel
{
    internal class ListHotel : INotifyPropertyChanged
    {
        List<Hotel> hotelList;
        int countHotel;
        int countOnPage = 10;
        int pageNumber = 1;
        int maxCountPage;

        public ListHotel()
        {
            hotelList = GlobalData.ConnectionDB.Hotel.Take(countOnPage).ToList();
            hotelList.ForEach(x => x.IsChecked = false);
            countHotel = GlobalData.ConnectionDB.Hotel.ToList().Count;
            maxCountPage = countHotel / countOnPage + Convert.ToInt32(countHotel % countOnPage != 0);
        }

        public List<Hotel> HotelList
        {
            get => hotelList;
            set
            {
                hotelList = value;
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(HotelList)));

            }
        }

        public int CountOnPage
        {
            get => countOnPage; 
            set
            {
                if(value > 0)
                {
                    countOnPage = value;
                    CountMaxPage();
                    SelectedHotelOnPage();
                }
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(CountOnPage)));
            }
        }

        public int PageNumber { 
            get => pageNumber; 
            set
            {
                if(value > 0)
                {
                    pageNumber = value;
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(PageNumber)));
                    SelectedHotelOnPage();
                }
                if(value > maxCountPage)
                {
                    pageNumber = maxCountPage;
                    SelectedHotelOnPage();
                }
            }
        }

        public int CountPage { 
            get => maxCountPage;
            set
            {
                maxCountPage = value;
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(CountPage)));
            }
        }

        /// <summary>
        /// Выборка списка отелей относительно страницы и кол-ва эл-ов на ней.
        /// </summary>
        private void SelectedHotelOnPage()
        {
            HotelList = GlobalData.ConnectionDB.Hotel.ToList()
                .Skip((PageNumber - 1)* CountOnPage).Take(CountOnPage).ToList();
        }

        private void CountMaxPage()
        {
            CountPage = countHotel / countOnPage + Convert.ToInt32(countHotel % countOnPage != 0);
            if(PageNumber > maxCountPage)
            {
                PageNumber = maxCountPage;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
