using CommunityToolkit.Mvvm.Input;
using pavesys_iRAP.DTO;
using System.Collections.Generic;
using System.Linq;
using System;
using Avalonia.Notification;
using pavesys_iRAP.Helper;
using Avalonia.Controls;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Diagnostics;



namespace pavesys_iRAP.ViewModels
{
    public partial class LoginPageViewModel : ViewModelBase
    {
        public bool authenticated;
        public string txtLogin { get; set; }
        public string txtPassword { get; set; }
        public IEnumerable<User> users { get; set; }
        [ObservableProperty]
        private bool isPopUpNotOn;
        public INotificationMessageManager Manager { get; } = new NotificationMessageManager();


       
        public LoginPageViewModel(IEnumerable<User> Users)
        {
            users = Users;
            authenticated = false;
            IsPopUpNotOn = true;
        }

        public async Task<bool> TryLogin()
        {
            if (CrudHelper.dbCtx.Database.CanConnect())
            {
                var userDB = (from usr in users
                              where usr.Login == txtLogin
                                && usr.Password == txtPassword
                                && usr.Active == 1
                              select usr).FirstOrDefault();
                if (userDB != null)
                {
                    authenticated = true;
                    return true;
                }

                else
                {
                    IsPopUpNotOn = false;

                    if (await DialogHelper.ShowOkDialog("ErrorLogin", "NoUserPass", MsBox.Avalonia.Enums.Icon.Error) == MsBox.Avalonia.Enums.ButtonResult.Ok)
                        IsPopUpNotOn = true;
                    return false;
                }
            }
            else
            {
                IsPopUpNotOn = false;

                if (await DialogHelper.ShowOkDialog("ErrorDatabase", "NotConnectedDatabase", MsBox.Avalonia.Enums.Icon.Error) == MsBox.Avalonia.Enums.ButtonResult.Ok)
                    IsPopUpNotOn = true;
                return false;
            }
        }
    }
}
