using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using PhilExample.Interfaces;
using PhilExampleCrawler.Common.Interfaces;
using PhilExampleCrawler.Common.Models;
using Xamarin.Forms;

namespace PhilExample.VMs
{
    internal class SelectRadiusVM : BaseVM, ICallbackPageVM<ICategory>
    {
        private readonly IPhExStorage _storage = DependencyService.Get<IPhExStorage>();
        private readonly IExamplePageService _ekaService = DependencyService.Get<IExamplePageService>();


        public event EventHandler<ICategory> OnPopped;
        public ICommand CloseCommand { get; }
        public ICommand SelectRadiusCommand { get; }


        private IEnumerable<Category> _radii;
        public List<CategoryMiniVM> Radii { get; } = new List<CategoryMiniVM>();

        bool _popupFinished = false;


        public SelectRadiusVM()
        {
            CloseCommand = new Command(async () => await CloseAsync());
            SelectRadiusCommand = new Command(SelectRadiusAsync);
        }

        public override async Task OnAppearingAsync()
        {
            _radii = await _storage.GetRadiiAsync();

            foreach (var radius in _radii)
                Radii.Add(new CategoryMiniVM(radius, SelectRadiusCommand, radius.ID,
                                             showArrow: false));
        }

        private async void SelectRadiusAsync(object radiusID)
        {
            if ((int)radiusID < 0)
            {
                OnPopped?.Invoke(this, _ekaService.GetDefaultCategory());
                await Shell.Current.GoToAsync("..");
                return;
            }

            ICategory selectedRadius = _radii.FirstOrDefault(x => x.ID == (int)radiusID);
            if (selectedRadius != null)
            {
                OnPopped?.Invoke(this, selectedRadius);
                await Shell.Current.GoToAsync("..");
            }
        }

        private async Task CloseAsync()
        {
            if (_popupFinished)
                return;
            _popupFinished = true;

            OnPopped?.Invoke(this, null);
            await Shell.Current.GoToAsync("..");
        }
    }
}

