using System.IO;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using C1.Silverlight;

namespace PdfExport
{
    public partial class Page : UserControl
    {
        const string RESOURCE_PATH = "PdfExport.Resources.";

        public Page()
        {
            InitializeComponent();

            // populate combo with list of html docs
            int len = RESOURCE_PATH.Length;
            foreach (var res in Assembly.GetExecutingAssembly().GetManifestResourceNames())
            {
                if (res.EndsWith("htm"))
                {
                    _cmb.Items.Add(res.Substring(len));
                }
            }
        }

        private void _cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // load and show a new document
            string res = RESOURCE_PATH + _cmb.SelectedItem.ToString();
            using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(res)))
            {
                _rtb.Html = sr.ReadToEnd();
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Start loading animation...
            LoadingAnimation.Begin();

            // send html document to server
            WebClient wc = new WebClient();
            wc.UploadStringAsync(Extensions.GetAbsoluteUri("PdfConverter.ashx"), _rtb.Html);
            wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
        }

        void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            // stop loading animation
            LoadingAnimation.Stop();

            if (e.Error == null)
            {
                // get pdf uri
                var uri = Extensions.GetAbsoluteUri(e.Result);

                // show it in a new window ("_self" would use the current one)
                string target = "_blank";
                System.Windows.Browser.HtmlPage.Window.Navigate(uri, target);
            }
        }
    }
}
