using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Security.Claims;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using DotVVM.Framework.ViewModel;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.ViewModel.Validation;
using Microsoft.AspNetCore.Identity;
using ElectroShop.Services;
using ElectroShop.Resources;

namespace ElectroShop.ViewModels.Authentication
{
    public class SignInViewModel : MasterPageViewModel
    {

        private readonly UserService userService;

        public SignInViewModel(UserService userService)
        {
            this.userService = userService;
        }

        [Required]
        public string UserName { get; set; }
        public string Password { get; set; }

        //metoda autentikaci, ktera kontroluje username, role uzivatele a jeho heslo. Pri uspesne autorizaci presmeruje
        //uzivatele do jeho pracovni stranky, v opacnem pripade vychodi chybovou hlasku. 
        public async Task SignIn()
        {
            var user = userService.GetUserByUsername(UserName);
            if (user == null)
            {
                ValidationErrors = new List<string>() { Texts.Incorrect_Login };
                return;
            }
            var role = userService.GetRoleByUsername(UserName);
            if (role == null)
            {
                ValidationErrors = new List<string>() { Texts.Incorrect_Login };
                return;
            }
            var identity = userService.SignIn(user, role, Password);
            if (identity == null)
            {
                ValidationErrors = new List<string>() { Texts.Incorrect_Login };
                return;
            }
            else
            {
                await Context.GetAuthentication().SignInAsync(IdentityConstants.ApplicationScheme, new ClaimsPrincipal(identity));
                Context.RedirectToRoute("Default", allowSpaRedirect: false);
            }
        }
    }
}
