using System.Linq;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V7.Preferences;
using Android.Views;
using MvvmCross.Droid.Shared.Attributes;
using MvvmCross.Droid.Support.V7.Preference;
using SocialManiac.Core.Services;
using SocialManiac.Core.ViewModels;
namespace SocialManiac.UI.Droid.Fragments
{
    [MvxFragment(typeof (MainViewModel), Resource.Id.content_frame, true)]
    [Register("socialmaniac.ui.droid.fragments.PreferenceFragment")]
    public class PreferenceFragment : BaseFragment<PreferenceViewModel>
    {
        protected override int FragmentId
        {
            get { return Resource.Layout.fragment_preference; }
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            Context.SetTheme(Resource.Style.MyTheme);
            FragmentManager.BeginTransaction()
            .Replace(Resource.Id.preference_content_frame, new SettingsPreference())
            .Commit();

            return base.OnCreateView(inflater, container, savedInstanceState);
        }

        public class SettingsPreference : MvxPreferenceFragmentCompat,
            ISharedPreferencesOnSharedPreferenceChangeListener
        {
            public override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                PreferenceScreen.SharedPreferences.RegisterOnSharedPreferenceChangeListener(this);
                
            }

            public override void OnDestroy()
            {
                PreferenceScreen.SharedPreferences.UnregisterOnSharedPreferenceChangeListener(this);
                base.OnDestroy();
            }


            public override void OnCreatePreferences(Bundle savedInstanceState, string rootKey)
            {
                AddPreferencesFromResource(Resource.Xml.preferences);

                PreferenceCategory preferenceSearchCategory = (PreferenceCategory)FindPreference("pref_search");

                ListPreference listCountryPreference = new ListPreference(Context);
                ListPreference listCityPreference = new ListPreference(Context);
                ListPreference listAgeFromPreference = new ListPreference(Context);
                ListPreference listAgeToPreference = new ListPreference(Context);

                var counties = BusService.VkService.Countries;
                var countiesId = counties.Select(country => country.Id.ToString());
                var countiesNames = counties.Select(country => country.Title);
                listCountryPreference.SetEntries(countiesNames.ToArray());
                listCountryPreference.SetEntryValues(countiesId.ToArray());
                listCountryPreference.SetDefaultValue("2");
                listCountryPreference.Title = "Ñòðàíà";
                listCountryPreference.DialogTitle = "Âûáåðèòå ñòðàíó";
                listCountryPreference.Key = "pref_search_country";
                listCountryPreference.Summary = "%s";

                SetCitiesList(listCityPreference);

                listCityPreference.Title = "Ãîðîä";
                listCityPreference.DialogTitle = "Âûáåðèòå ãîðîä";
                listCityPreference.Key = "pref_search_city";
                listCityPreference.Summary = "%s";

                var listAgeFromValues = Enumerable.Range(14, 80 - 13).Select(n => n.ToString()).ToArray();
                listAgeFromPreference.SetEntryValues(listAgeFromValues);
                listAgeFromPreference.SetEntries(listAgeFromValues);
                listAgeFromPreference.SetDefaultValue("18");
                listAgeFromPreference.Title = "Âîçðàñò - îò";
                listAgeFromPreference.DialogTitle = "Âûáåðèòå âîçðàñò";
                listAgeFromPreference.Key = "pref_search_ageFrom";
                listAgeFromPreference.Summary = "%s";

                listAgeToPreference.Title = "Âîçðàñò - äî";
                listAgeToPreference.SetDefaultValue("18");
                listAgeToPreference.DialogTitle = "Âûáåðèòå âîçðàñò";
                listAgeToPreference.Key = "pref_search_ageTo";
                listAgeToPreference.Summary = "%s";

                SetAgeToList(listAgeToPreference);

                preferenceSearchCategory.AddPreference(listAgeFromPreference);

                preferenceSearchCategory.AddPreference(listAgeToPreference);
                preferenceSearchCategory.AddPreference(listCountryPreference);
                preferenceSearchCategory.AddPreference(listCityPreference);
            }


            private void SetAgeToList(ListPreference preference)
            {
                var settings = BusService.SettingsService.GetSettings();
                var correctAgeFrom = int.Parse(settings.SearchAgeFrom);
                var correctAgeTo = settings.SearchAgeTo;
                var listAgeToValues = Enumerable.Range(correctAgeFrom, 81 - correctAgeFrom).Select(n => n.ToString()).ToArray();
                preference.SetEntryValues(listAgeToValues);
                preference.SetEntries(listAgeToValues);
                if(!string.IsNullOrEmpty(correctAgeTo) && int.Parse(correctAgeTo) < correctAgeFrom)
                {
                    preference.SetValueIndex(0);
                }
            }

            private void SetCitiesList(ListPreference preference)
            {
                var cities = BusService.VkService.Cities;
                var citiesId = cities.Select(city => city.Id.ToString());
                var citiesNames = cities.Select(city => city.Title);
                preference.SetEntries(citiesNames.ToArray());
                preference.SetEntryValues(citiesId.ToArray());
                preference.SetDefaultValue(citiesId.First());
            }

            public void OnSharedPreferenceChanged(ISharedPreferences sharedPreferences, string key)
            {
                switch (key)
                {
                    case "pref_search_country":
                        BusService.VkService.ReloadCitiesAsync(int.Parse(BusService.SettingsService.GetSettings().SearchCountry));
                        var citiesPref = (ListPreference) FindPreference("pref_search_city");
                        SetCitiesList(citiesPref);
                        citiesPref.SetValueIndex(0);
                        break;
                    case "pref_search_ageFrom":
                        var ageToPref = (ListPreference)FindPreference("pref_search_ageTo");
                        SetAgeToList(ageToPref);
                        break;
                    default:
                        return;
                }
            }
        }
    }

}