﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using ResxTranslator.Common;

namespace ResxTranslator
{
	[Controller(typeof(AddCultureDialogController))]
    public partial class AddCultureDialog : Form, IAddCultureDialogView
    {
    	/// <summary>
    	/// Initializes a new instance of the <see cref="AddCultureDialog"/> class.
    	/// </summary>
    	public AddCultureDialog()
        {
            InitializeComponent();
        }

		public AddCultureDialogModel Model { get; set; }

        private void AddCultureDialog_Load(object sender, EventArgs e)
        {
			cbCultures.Items.AddRange(Model.AvailableCultures);
			btnAddNeutralCulture.Enabled = !Model.IsNeutralCultureUsed;
        }

		private void btnOk_Click(object sender, EventArgs e)
		{
			Model.SelectedCulture = GetSelectedCulture();
        }

		private void btnAddNeutralCulture_Click(object sender, EventArgs e)
		{
			Model.SelectedCulture = CultureInfo.InvariantCulture;
        }

        /// <summary>
        /// Gets the selected culture based on the selected item in the drop down list.
        /// </summary>
        /// <returns>A culture.</returns>
        private CultureInfo GetSelectedCulture()
        {
            CultureInfo selected = cbCultures.SelectedItem as CultureInfo;
            return selected ?? GetSelectedCultureByText();
        }

        /// <summary>
        /// Gets the selected culture based on the selected text in the drop down list.
        /// </summary>
        /// <remarks>
        /// This is used when the user types in the culture instead of selecting it from the list.
        /// </remarks>
        /// <returns>A culture.</returns>
        private CultureInfo GetSelectedCultureByText()
        {
            string text = cbCultures.Text;
            return !string.IsNullOrWhiteSpace(text) && Model.AvailableCultures.Contains(text) ?
                new CultureInfo(text) : null;
        }
    }
}
