using GMCabsDriverAssistant.Models;
using GMCabsDriverAssistant.Services;
using GMCabsDriverAssistant.Utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GMCabsDriverAssistantSolution.ViewModels
{
    class NotificationsViewModel : BaseViewModel
    {
        #region Fields
        private GMCabsDriverService gmCabsDriverService;
        private NotificationDto _selectedNotification;
        #endregion

        #region Properties
        public ObservableCollection<NotificationDto> Notifications { get; set; }
        public Command MarkNotificationAsViewedCommand { get; }

        public NotificationDto SelectedNotification
        {
            get => _selectedNotification;
            set => SetProperty(ref _selectedNotification, value);
        }
        #endregion

        #region Constructor
        public NotificationsViewModel()
        {
            Title = "Notifications";
            Notifications = new ObservableCollection<NotificationDto>();
            MarkNotificationAsViewedCommand = new Command(OnMarkNotificationAsViewedClicked);
            GetNotifications();
        }
        #endregion

        #region Methods
        private async void GetNotifications()
        {
            string appToken = Preferences.Get(SecureStorageData.Token, "");
            gmCabsDriverService = new GMCabsDriverService();
            Notifications.Clear();
            List<NotificationDto> notifications = await gmCabsDriverService.GetNotifications(appToken);
            if (notifications.Count > 0)
            {
                foreach (NotificationDto notification in notifications)
                {
                    Notifications.Add(notification);
                }
                SelectedNotification = Notifications[0];
            }
            else
            {
                await Shell.Current.GoToAsync("..");
            }
        }

        private async void OnMarkNotificationAsViewedClicked(object obj)
        {
            string appToken = Preferences.Get(SecureStorageData.Token, "");
            gmCabsDriverService = new GMCabsDriverService();

            bool isSuccess = await gmCabsDriverService.MarkNotificationAsViewed(appToken, SelectedNotification.Id);
            if (isSuccess)
            {
                Notifications.Remove(SelectedNotification);
                if (Notifications.Count > 0)
                {
                    SelectedNotification = Notifications[0];
                }
                else
                {
                    await Shell.Current.GoToAsync("..");
                }
            }
        }
        #endregion


    }
}
