using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using wpf_listbox.models;
using System.Threading.Tasks;
using System;
using System.Formats.Asn1;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Windows.Media;


namespace wpf_listbox
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;
        private void Invalidate()
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("PeopleList"));
        }
        public string selectedGender = "Пол";
        public PeopleAge? selectedAge = null;
        public string selectedPlace = "Место";

        private IEnumerable<People> _PeopleList;
        public IEnumerable<People> PeopleList
        {
            get
            {
                var res = _PeopleList;

                // фильтруем по возрасту
                res = res
                     .Where(c => (c.Gender == selectedGender || selectedGender == "Пол"))
                     .Where(c => (selectedAge == null || (c.Age >= selectedAge.AgeFrom && c.Age < selectedAge.AgeTo)))
                     .Where(c => (c.Place == selectedPlace || selectedPlace == "Место"));
                // если фильтр не пустой, то ищем ВХОЖДЕНИЕ подстроки поиска в кличке без учета регистра
                if (searchFilter != "")
                    res = res.Where(c => c.Name.IndexOf(
                        searchFilter,
                        StringComparison.OrdinalIgnoreCase) >= 0 || c.Gender.IndexOf(
                        searchFilter,
                        StringComparison.OrdinalIgnoreCase) >= 0 || c.Place.IndexOf(
                        searchFilter,
                        StringComparison.OrdinalIgnoreCase) >= 0);
                if (sortAsc) res = res.OrderBy(c => c.Price);
                else res = res.OrderByDescending(c => c.Price);
                if (sortAsc) res = res.OrderBy(c => c.Price);
                else res = res.OrderByDescending(c => c.Price);

                return res;
            }
            set
            {
                _PeopleList = value;
            }
        }


        public List<PeopleGender> PeopleGenderList { get; set; }
        public List<PeopleAge> PeopleAgeList { get; set; }
        public List<PeoplePlace> PeoplePlaceList { get; set; }
        public MainWindow()
        {

            InitializeComponent();
            DataContext = this;
            Globals.dataProvider = new JSONDataProvider();
            PeopleList = Globals.dataProvider.getPeople();
            PeopleGenderList = Globals.dataProvider.getGender().ToList();
            PeopleGenderList.Insert(0, new PeopleGender { title = "Пол" });
            PeopleAgeList = Globals.dataProvider.getAge().ToList();
            PeoplePlaceList = Globals.dataProvider.getPlace().ToList();
            PeoplePlaceList.Insert(0, new PeoplePlace { title = "Место" });
            List<string> styles = new List<string> { "light", "dark" };
            styleBox.SelectionChanged += ThemeChange;
            styleBox.ItemsSource = styles;
            styleBox.SelectedItem = "dark";

            Style buttonStyle = new Style();
            buttonStyle.Setters.Add(
                new Setter
                {
                    Property = Control.FontFamilyProperty,
                    Value = new FontFamily("Verdana")
                });
            buttonStyle.Setters.Add(
                new Setter
                {
                    Property = Control.MarginProperty,
                    Value = new Thickness(10)
                });
            buttonStyle.Setters.Add(
                new Setter
                {
                    Property = Control.BackgroundProperty,
                    Value = new SolidColorBrush(Colors.LightGoldenrodYellow)
                });
            buttonStyle.Setters.Add(
                new Setter
                {
                    Property = Control.ForegroundProperty,
                    Value = new SolidColorBrush(Colors.DarkGreen)
                });

            button1.Style = buttonStyle;
            button2.Style = buttonStyle;

        }
        private void ThemeChange(object sender, SelectionChangedEventArgs e)
        {
            string style = styleBox.SelectedItem as string;
            // определяем путь к файлу ресурсов
            var uri = new Uri(style + ".xaml", UriKind.Relative);
            // загружаем словарь ресурсов
            ResourceDictionary resourceDict =
                Application.LoadComponent(uri) as ResourceDictionary;
            // очищаем коллекцию ресурсов приложения
            Application.Current.Resources.Clear();
            // добавляем загруженный словарь ресурсов
            Application.Current.Resources.MergedDictionaries.Add(resourceDict);
        }

        private string currentStyle = "StackStyle";

        private void ToggleView_Click(object sender, RoutedEventArgs e)
        {
            currentStyle = currentStyle == "StackStyle" ? "WrapStyle" : "StackStyle";
            var newStyle = (Style)TryFindResource(currentStyle);
            if (newStyle != null)
                PeopleListBox.Style = newStyle;
        }

        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();

        }
        private string searchFilter = "";

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button clickedButton = (Button)sender;
            MessageBox.Show(clickedButton.Content.ToString());
        }
        private void SearchFilter_KeyUp(object sender, KeyEventArgs e)
        {
            searchFilter = SearchFilterTextBox.Text;
            Invalidate();
        }

        private void GenderFilterComboBox_SelectionChanged_1(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            selectedGender = (GenderFilterComboBox.SelectedItem as PeopleGender).title;
            Invalidate();
        }
        private void AgeFilterComboBox_SelectionChanged_2(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            selectedAge = AgeFilterComboBox.SelectedItem as PeopleAge;
            Invalidate();
        }
        private void PlaceFilterComboBox_SelectionChanged_3(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            selectedPlace = (PlaceFilterComboBox.SelectedItem as PeoplePlace).title;
            Invalidate();
        }
        private bool sortAsc = true;

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            sortAsc = (sender as RadioButton).Tag.ToString() == "1";
            Invalidate();
        }



    }


    public class LocalDataProvider : IDataProvider
    {
        public IEnumerable<PeopleGender> getGender()
        {
            return new PeopleGender[]
            {
                new PeopleGender()
                {
                    title="Ж"

                },
                new PeopleGender()
                {
                    title="М"
                }
            };
        }
        public IEnumerable<PeopleAge> getAge()
        {
            return new PeopleAge[]
            {
                new PeopleAge()
                {
                    title="Все возраста",
                    AgeFrom=0,
                    AgeTo=99

                },



                new PeopleAge()
                {
                    title="Подростки",
                    AgeFrom=15,
                    AgeTo=18

                },
                new PeopleAge()
                {
                    title="Молодые",
                    AgeFrom=18,
                    AgeTo=30

                },
                new PeopleAge()
                {
                    title="В Возврасте",
                    AgeFrom=30,
                    AgeTo=99

                }

            };

        }
        public IEnumerable<PeoplePlace> getPlace()
        {
            return new PeoplePlace[]
            {
                new PeoplePlace()
                {
                    title="Набережная"

                },
                new PeoplePlace()
                {
                    title="Йолка"
                },
                new PeoplePlace()
                {
                    title="Бульвар"
                },
                new PeoplePlace()
                {
                    title="ЙОТК"
                },
               new PeoplePlace()
                {
                    title="Планета"
                },
               new PeoplePlace()
                {
                    title="Ремзавод"
                },
               new PeoplePlace()
                {
                    title="Медведево"
                },
               new PeoplePlace()
                {
                    title="Пляж"
                },

            };
        }
        public IEnumerable<People> getPeople()
        {
            return new People[]{
            new People
            {
                Age=19,
                Name="Марина",
                Gender="Ж",
                Price=500,
                Place="Набережная"
            },
            new People
            {
                Price=9600,
                Name="Вика",
                Age=21,
                Gender="Ж",
                Place="Йолка"
            },
            new People
            {
                Price=50,
                Name="Кристина",
                Age=17,
                Gender="Ж",
                Place="Планета"
            },
            new People
            {
                Price=2000,
                Name="Анджелика",
                Age=16,
                Gender="Ж",
                Place="Бульвар"
            },
            new People
            {
                Price=1500,
                Name="Костя",
                Age=15,
                Gender="М",
                Place="Бульвар"
            },
            new People
            {
                Price=5000,
                Name="Вероника",
                Age=25,
                Gender="Ж",
                Place="Набережная"
            },
            new People
            {
                Price=1000,
                Name="Савелий",
                Age=20,
                Gender="М",
                Place="Пляж"
            },
            new People
            {
                Price=1500,
                Name="Александр",
                Age=39,
                Gender="М",
                Place="ЙОТК"
            },
            new People
            {
                Price=500,
                Name="Евгений",
                Age=18,
                Gender="М",
                Place="Медведево"
            },
            new People
            {
                Price=2500,
                Name="Давид",
                Age=18,
                Gender="М",
                Place="Ремзавод"
            },

        };

        }

        IEnumerable<models.People> IDataProvider.getPeople()
        {
            throw new NotImplementedException();
        }
    }
    public class JSONDataProvider : LocalDataProvider, IDataProvider
    {
        private List<People> _PeopleList;

        public JSONDataProvider()
        {
            var serializer = new DataContractJsonSerializer(typeof(People[]));
            using (var sr = new StreamReader("./data.json"))
            {
                _PeopleList = ((People[])serializer.ReadObject(sr.BaseStream)).ToList();
            }
        }

        public IEnumerable<People> getPeople()
        {
            return _PeopleList;
        }
    }

}