using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Windows.Browser;
using System.Windows.Controls;
using C1DataGrid_Demo2010;

namespace C1DataGrid_Localization
{
    public partial class Page : UserControl
    {
        public Page()
        {
            // note: start with a culture present in the Resources

            InitializeComponent();
            DataContext = GetProducts();
            Dispatcher.BeginInvoke(() =>
            {
                CultureInfo[] availableNeutralLanguages = GetCultures(",ar,cs,da,de,el,en,es,fi,fr,he,it,ja,nl,no,pl,pt,ro,ru,sk,sv,tr,zh,zh-Hans,zh-Hant");
                cmbColumns.ItemsSource = availableNeutralLanguages;
                cmbColumns.SelectedItem = availableNeutralLanguages[0];
                foreach (var neutrallanguage in availableNeutralLanguages)
                {
                    if (neutrallanguage.Name == Thread.CurrentThread.CurrentUICulture.Name)
                    {
                        cmbColumns.SelectedItem = neutrallanguage;
                        break;
                    }
                }
                cmbColumns.SelectionChanged += (s, e) =>
                {
                    Thread.CurrentThread.CurrentUICulture = e.AddedItems[0] as CultureInfo;
                    App.SaveCulture();
                    ((ScriptObject)HtmlPage.Window.GetProperty("location")).Invoke("reload");
                };
            });
        }

        private CultureInfo[] GetCultures(string p)
        {
            List<CultureInfo> result = new List<CultureInfo>();
            foreach (var cultureName in p.Split(','))
            {
                CultureInfo culture = new CultureInfo(cultureName);
                result.Add(culture);
            }
            return result.ToArray();
        }

        public static IEnumerable<Product> GetProducts()
        {
            IEnumerable<Product> products = Data.GetProducts((product) => !string.IsNullOrEmpty(product.Element("ProductModelID").Value));
            foreach (var product in products)
            {
                product.ExpirationDate = GetDate(product.StandardCost);
                product.Available = GetAvailable(product.Name);
            }
            return products;
        }

        private static bool? GetAvailable(string seed)
        {
            return (seed.Length % 3 == 0 ? (bool?)true : (seed.Length % 3 == 1 ? (bool?)false : (bool?)null));
        }

        private static DateTime? GetDate(double seed)
        {
            return new DateTime(DateTime.Now.Ticks - ((long)seed * 10000000000));
        }
    }

    public class Models : List<Model>
    {
        public Models()
        {
            foreach (var model in Data.GetModels())
            {
                Add(model);
            }
        }
    }
}
