using GMCabsDriverAssistant.Models;
using GMCabsDriverAssistant.Services;
using GMCabsDriverAssistant.Utils;
using GMCabsDriverAssistantSolution.Models.Rydo;
using GMCabsDriverAssistantSolution.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace GMCabsDriverAssistantSolution.ViewModels
{
    class BookingsViewModel : BaseViewModel
    {
        #region Fields
        private string startSuburb;

        private string endSuburb;

        private float distance;
        private string formattedDistance;

        private bool isFutureBooking;

        private BookingDto selectedBooking;
        #endregion

        #region Properties

        public string StartSuburb
        {
            get => startSuburb;
            set => SetProperty(ref startSuburb, value);
        }
        public string EndSuburb
        {
            get => endSuburb;
            set => SetProperty(ref endSuburb, value);
        }
        public float Distance
        {
            get => distance;
            set => SetProperty(ref distance, value);
        }
        public string FormattedDistance
        {
            get => (distance >= 1000) ? $"{distance / 1000:0.##}k" : $"{(int)distance}m";
            set => SetProperty(ref formattedDistance, value);
        }
        public bool IsFutureBooking
        {
            get => isFutureBooking;
            set => SetProperty(ref isFutureBooking, value);
        }
        public BookingDto SelectedBooking
        {
            get => selectedBooking;
            set
            {
                SetProperty(ref selectedBooking, value);
                OnBookingSelected(value);
            }
        }
        public Command OnRefreshClicked { get; }
        public ObservableCollection<BookingDto> Bookings { get; }
        public Command<BookingDto> BookingTapped { get; }
        public double CurrentLat { get; set; }
        public double CurrentLng { get; set; }
        #endregion

        #region Constructor
        public BookingsViewModel()
        {
            Title = "Available Bookings";
            Bookings = new ObservableCollection<BookingDto>();
            OnRefreshClicked = new Command(async () => { await GetBookings(); });
            BookingTapped = new Command<BookingDto>(OnBookingSelected);
        }
        #endregion

        #region Methods
        public void OnAppearing()
        {
            //IsBusy = true;
            SelectedBooking = null;
            Task.Run(async () =>
            {
                await GetBookings();
            });
        }

        private async Task GetBookings()
        {
            List<string> seenBookingList = new List<string>();
            var seenBooking = Preferences.Get(SecureStorageData.UnSeenBooking, "");
            if (!String.IsNullOrEmpty(seenBooking))
            {
                var arrList = seenBooking.Split(',');
                if (arrList != null)
                {
                    foreach (var item in arrList)
                    {
                        seenBookingList.Add(item);
                    }

                }
            }
            string rydoAccessToken = Preferences.Get(EftposLoginResponse.RYDO_ACCESS_TOKEN, "");
            Guid driverId = Guid.Parse(Preferences.Get(LoginResponseDto.USER_CODE, ""));
            GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
            Bookings.Clear();
            var bookings = await gmCabsDriverService.GetBookings(rydoAccessToken, driverId, CurrentLat, CurrentLng);
            if (bookings.Count > 0)
            {
                foreach (BookingDto booking in bookings)
                {
                    if (seenBookingList.Count > 0 && seenBookingList.Contains(booking.BookingId.ToString()))
                    {
                        booking.IsSeenBooking = false;
                    }
                    else
                    {
                        booking.IsSeenBooking = true;
                    }
                    Bookings.Add(booking);
                }
            }
            else
            {
                Preferences.Set(SecureStorageData.UnSeenBooking, "");
                await Shell.Current.GoToAsync("..");
            }

        }

        async void OnBookingSelected(BookingDto booking)
        {
            if (booking == null)
                return;

            // This will push the ItemDetailPage onto the navigation stack

            var seenBooking = Preferences.Get(SecureStorageData.UnSeenBooking, "");
            if (String.IsNullOrEmpty(seenBooking))
            {
                seenBooking = booking.BookingId.ToString();
            }
            else
            {
                seenBooking = seenBooking + "," + booking.BookingId.ToString();
            }
            Preferences.Set(SecureStorageData.UnSeenBooking, seenBooking);
            //    await Shell.Current.GoToAsync($"{nameof(BookingDetailsPage)}?{nameof(BookingDetailViewModel.BookingId)}={booking.BookingId:N}");
            string bookingJson = JsonSerializer.Serialize(booking);
            await Shell.Current.GoToAsync($"{nameof(BookingDetailsPage)}?{nameof(BookingDetailViewModel.BookingJson)}={bookingJson}");
        }
        #endregion
    }
}
