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.ElectronicComponentCathegory
{
    [Authorize(Roles = "Warehouseman")]
    public class CreateViewModel : MasterPageViewModel
    {
        private readonly CathegoryService cathegoryService;

        public ElectronicComponentCathegoryModel Model { get; set; } = new ElectronicComponentCathegoryModel();

        public List<string> ParameterNames { get; set; }

        public CreateViewModel(CathegoryService cathegoryService)
        {
            this.cathegoryService = cathegoryService;
            ParameterNames = new List<string>() { };
        }

        public async Task Add()
        {
            if (Model.Name == null)
            {
                ValidationErrors = new List<string>() { Texts.EnterName };
                return;
            }

            if (cathegoryService.ContainsAlreadyAName(Model.Name))
            {
                ValidationErrors = new List<string>() { Texts.NameAlreadyUsed };
                return;
            }


            string parameterNamesParsed = "";
            int count = 0;
            foreach (string parameterName in ParameterNames)
            {
                if (parameterName == null || parameterName == String.Empty)
                {
                    ValidationErrors = new List<string>() { Texts.AddParameterName };
                    return;
                }

                string cathegoryNameParsed = Helper.ParseParametersValuesOrNames(parameterName);
                count++;
                if (count == ParameterNames.Count)
                {
                    parameterNamesParsed = parameterNamesParsed + cathegoryNameParsed;
                }
                else
                {
                    parameterNamesParsed = parameterNamesParsed + cathegoryNameParsed + ";";
                }
            }

            if (parameterNamesParsed != "")
            {
                Model.ParametersNames = parameterNamesParsed;
            }

            cathegoryService.Create(Model);
            Context.RedirectToRoute("CathegoriesManagement");
        }

        public async Task AddParameterName()
        {
            ParameterNames.Add("");
        }
    }
}
