﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Resources;
using ScaffoldR.Core.Views;

namespace HartmannSolutions.Web.Mvc.ViewModels
{
    public class LanguageSelectorViewModel : IViewModel
    {
        public IList<SelectListItem> Languages { get; set; }
    }

    internal sealed class HandleLanguageSelectorViewModel : IHandleViewModel<LanguageSelectorViewModel>
    {
        private const string LanguageResourcePrefix = "Language_";

        private readonly ISet<string> _acceptedCultures;

        public HandleLanguageSelectorViewModel()
        {
            _acceptedCultures = LocalizationConfig.AcceptedCultures;
        }

        public LanguageSelectorViewModel Handle()
        {
            var currentCulture = Thread.CurrentThread.CurrentCulture.Name;
            var viewModel = new LanguageSelectorViewModel
            {
                Languages = new List<SelectListItem>(_acceptedCultures.Count)
            };

            foreach (var item in _acceptedCultures.Select(culture => new SelectListItem
            {
                Value = culture,
                Text = GetLanguageResource(culture),
                Selected = (currentCulture == culture)
            }))
            {
                viewModel.Languages.Add(item);
            }

            return viewModel;
        }

        private static string GetLanguageResource(string cultureName)
        {
            return GenericResources.ResourceManager.GetString(LanguageResourcePrefix + cultureName);
        }
    }
}