using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using NotepadEnhanced.Helpers;

namespace NotepadEnhanced.Localization
{
    class SupportedCultures
    {
        private readonly List<CultureInfo> _cultures = new List<CultureInfo>();

        public SupportedCultures()
        {
            SetSupportedCultures();
        }

        private void SetSupportedCultures()
        {
            try
            {
                // Find directories with only two letters in the names
                string[] directories = Directory.GetDirectories(Application.StartupPath, "??", SearchOption.TopDirectoryOnly);

                // Add English manually as it is used as the default values
                _cultures.Add(CultureInfo.GetCultureInfo("en"));

                foreach (var langDirectory in directories.Select(dir => new DirectoryInfo(dir)))
                {
                    _cultures.Add(CultureInfo.GetCultureInfo(langDirectory.Name));
                }
            }
            catch (Exception ex)
            {
                MsgBox.Show(ex.Message);
            }
        }

        public string[] ToStringArray()
        {
            var stringList = new List<string>();

            for (int i = 0; i < _cultures.Count; i++)
            {
                string itemValue = _cultures[i].NativeName;

                // Set default culture index to set a combobox to the appropriate item
                // We need to check the parent for specific locals as well
                if (_cultures[i].Name.Equals(Thread.CurrentThread.CurrentCulture.Name) ||
                    (_cultures[i].Name.Equals(Thread.CurrentThread.CurrentCulture.Parent.Name)))
                {
                    DefaultCultureIndex = i;
                }

                stringList.Add(StringOps.CapitalizeFirstLetter(itemValue));
            }

            return stringList.ToArray();
        }

        public List<CultureInfo> All
        {
            get { return _cultures; }
        }

        /// <summary>
        /// The to string method must be called first before the index is set
        /// </summary>
        public int DefaultCultureIndex { get; private set; }
    }
}
