using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using FoxTube.Classes;
using Windows.Storage;
using System.Xml;
using Microsoft.AppCenter.Analytics;
using System.Globalization;

namespace FoxTube.Pages.SettingsPages
{
    /// <summary>
    /// Page with changelogs and dev messages
    /// </summary>
    public sealed partial class Inbox : Page
    {
        List<InboxItem> items = new List<InboxItem>();

        public Inbox()
        {
            InitializeComponent();
        }

        string GetLanguage()
        {
            if ((new[] { "ua", "ru", "by", "kz", "kg", "md", "lv", "ee" }).Contains(CultureInfo.InstalledUICulture.TwoLetterISOLanguageName))
                return "ru-RU";
            else
                return "en-US";
        }

        public async void LoadItems(string id = null)
        {
            try
            {
                XmlDocument doc = new XmlDocument();

                StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appx:///Assets/Data/Patchnotes.xml".ToUri());
                doc.Load(await file.OpenStreamForReadAsync());
                foreach (XmlElement e in doc["items"].ChildNodes)
                    items.Add(new InboxItem(
                        e.GetAttribute("version"),
                        e["content"][GetLanguage()].InnerText,
                        DateTime.Parse(e.GetAttribute("time"), CultureInfo.GetCultureInfo("en-US").DateTimeFormat)));

                doc.Load("http://foxgame-studio.000webhostapp.com/foxtube-messages.xml");
                foreach (XmlElement e in doc["posts"].ChildNodes)
                    items.Add(new InboxItem(
                        e["header"][GetLanguage()].InnerText,
                        e["content"][GetLanguage()].InnerText,
                        DateTime.Parse(e.GetAttribute("time"), CultureInfo.GetCultureInfo("en-US").DateTimeFormat),
                        e["id"].InnerText,
                        e["contentHeader"].InnerText));
            }
            catch (Exception e)
            {
                Analytics.TrackEvent("Failed to load inbox", new Dictionary<string, string>
                {
                    { "Exception", e.GetType().ToString() },
                    { "Message", e.Message },
                    { "StackTrace", e.StackTrace }
                });
            }

            items = items.OrderBy(item => item.TimeStamp).Reverse().ToList();
            items.ForEach(i => list.Items.Add(i));

            if (!string.IsNullOrWhiteSpace(id))
                list.SelectedItem = items.Find(i => i.Id == id);
        }

        private void filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (list == null)
                return;

            list.Items.Clear();
            CloseView();

            switch (filter.SelectedIndex)
            {
                case 0:
                    items.ForEach(i => list.Items.Add(i));
                    break;

                case 1:
                    List<InboxItem> messages = items.FindAll(i => i.Type == InboxItemType.Default);
                    messages.ForEach(i => list.Items.Add(i));
                    break;

                case 2:
                    List<InboxItem> notes = items.FindAll(i => i.Type == InboxItemType.PatchNote);
                    notes.ForEach(i => list.Items.Add(i));
                    break;
            }
        }

        private void list_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(list.SelectedItem is InboxItem item))
                return;

            OpenView(item.Title, item.Content);
        }

        void CloseView()
        {
            content.Text = "";
            title.Text = "";
            list.SelectedItem = null;
            block.Visibility = Visibility.Visible;

            if (grid.ColumnDefinitions[0].Width.Value == 0)
            {
                grid.ColumnDefinitions[1].Width = new GridLength(0);
                grid.ColumnDefinitions[0].Width = new GridLength(1, GridUnitType.Star);
            }
        }

        void OpenView(string header, string body)
        {
            content.Text = body;
            title.Text = header;
            block.Visibility = Visibility.Collapsed;

            if (grid.ColumnDefinitions[1].Width.Value == 0)
            {
                grid.ColumnDefinitions[0].Width = new GridLength(0);
                grid.ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Star);
            }
        }

        private void close_Click(object sender, RoutedEventArgs e)
        {
            CloseView();
        }

        private void VisualStateGroup_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)
        {
            if (e.NewState == null)
                CloseView();
        }

        private void Content_LinkClicked(object sender, Microsoft.Toolkit.Uwp.UI.Controls.LinkClickedEventArgs e)
        {
            Methods.ProcessLink(e.Link);
        }
    }
}
