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

namespace ElectroShop.ViewModels.User
{
    [Authorize(Roles = "Administrator")]
    public class CreateUserViewModel : MasterPageViewModel
    {
        private readonly UserService userService;
        public List<string> UserTypes { get; set; }

        public UserModel User { get; set; } = new UserModel();

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

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

        }
    }
}
