using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using DotVVM.Framework.Runtime.Filters;
using ElectroShop.DAL.Entities;
using ElectroShop.Models;
using ElectroShop.Resources;
using ElectroShop.Services;

namespace ElectroShop.ViewModels.User
{
    [Authorize(Roles = "Administrator")]
    public class EditUserViewModel : MasterPageViewModel
    {
        private readonly UserService userService;

        public UserModel User { get; set; }
        public string Username { get; set; }
        public List<string> UserTypes { get; set; }
        public string Name { get; set; }

        public EditUserViewModel(UserService userService)
        {
            this.userService = userService;
            UserTypes = Enum.GetValues(typeof(UserType))
            .Cast<UserType>()
            .Select(v => v.ToString())
            .ToList();
        }


        public override async Task PreRender()
        {
            Username = Context.Parameters["Username"].ToString();
            User = userService.GetUserModelByName(Username);
            await base.PreRender();
        }


        public async Task Edit()
        {
            if (User.Name == null || User.Name == String.Empty)
            {
                ValidationErrors = new List<string>() { Texts.EnterName };
                return;
            }
            if (User.Surname == null || User.Surname == String.Empty)
            {
                ValidationErrors = new List<string>() { Texts.EnterSurname };
                return;
            }
            if (User.Role == null)
            {
                ValidationErrors = new List<string>() { Texts.SelectRole };
                return;
            }
            var result = userService.EditUser(User);
            if (result.Succeeded)
            {
                Context.RedirectToRoute("UserManagement");
            }
            else
            {
                var list = new List<string>();
                foreach (var error in result.Errors)
                {
                    list.Add(error.Description);
                }
                ValidationErrors = list;
            }
        }
    }
}
