using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XamarinStudy.Models;

namespace XamarinStudy.Views
{
	[XamlCompilation(XamlCompilationOptions.Compile)]
	public partial class SampleListViewPage : ContentPage
	{
		private List<Food> foods;

		public SampleListViewPage()
		{
			InitializeComponent();
			InitInstance();
		}

		private void InitInstance()
		{
			//mainListView.ItemsSource = foods;
			//mainListView.Footer = foods;
			foods = GetFoodList();
			mainListView.BindingContext = foods;
			groupedListView.BindingContext = foods.OrderBy(f => f.Name).GroupBy(f => f.Flavor).ToList();
		}

	    private List<Food> GetFoodList()
		{
			List<Food> list = new List<Food>();
			list.Add(new Food() { Name = "냉면", Price = 10000, Flavor = "시원함" });
			list.Add(new Food() { Name = "모밀", Price = 80000, Flavor = "시원함" });
			list.Add(new Food() { Name = "국수", Price = 5000, Flavor = "얼큰함" });
			list.Add(new Food() { Name = "쫄면", Price = 5000, Flavor = "매콤함" });
			list.Add(new Food() { Name = "떡볶이", Price = 3000, Flavor = "매콤함" });
			list.Add(new Food() { Name = "라면", Price = 3000, Flavor = "매콤함" });
			list.Add(new Food() { Name = "짜장면", Price = 3000, Flavor = "달콤함" });
			list.Add(new Food() { Name = "떡라면", Price = 5000, Flavor = "매콤함" });
			list.Add(new Food() { Name = "짜장떡볶이", Price = 3000, Flavor = "달콤함" });

			return list;
		}

		private void mainListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
		{
			if (mainListView.SelectedItem == null)
				return;

			Food selected = (Food)mainListView.SelectedItem;
			DisplayAlert("맛", $"선택한 음식의 맛은 {selected.Flavor} 입니다.", "확인");
			mainListView.SelectedItem = null;
		}

		private void foodSearchBar_TextChanged(object sender, TextChangedEventArgs e)
		{
			mainListView.BindingContext = 
				foods.Where(food => food.Name.ToLower().Contains(e.NewTextValue.Replace(" ", "").ToLower())).ToList();
		}

		private void mainListView_Refreshing(object sender, EventArgs e)
		{
			foodSearchBar.Text = "";
			mainListView.BindingContext = GetFoodList();
			DisplayAlert("상태", "음식 리스트를 다시 불러왔습니다.", "확인");

			mainListView.EndRefresh();
		}
	}
}