using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace ImageLiveSearch
{
    public partial class Page : UserControl
    {
        private const string SEARCH_URL = "http://api.search.live.net/xml.aspx?AppId={0}&Market={1}&Query={2}&Sources=image";
        private const string APP_ID = "";

        private XNamespace mms = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/multimedia";
        private XNamespace s = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element";

        public Page()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string url = String.Format(SEARCH_URL,
                                        APP_ID,
                                        "cs-CZ",
                                        Uri.EscapeDataString( txtSearch.Text));

            WebRequest request = WebRequest.Create(new Uri(url));
            request.BeginGetResponse(OnData, request);
        }

        private void OnData(IAsyncResult e)
        {
            WebRequest request = (WebRequest)e.AsyncState;
            WebResponse response = (WebResponse)request.EndGetResponse(e);

            StreamReader data = new StreamReader(response.GetResponseStream());

            XDocument d = XDocument.Parse(data.ReadToEnd());
            var images = from i in d.Descendants(mms + "ImageResult")
                         select new Image
                         { 
                             Url = i.Element(mms + "Thumbnail").Element(mms + "Url").Value, 
                             Title = i.Element(mms + "Title").Value 
                         };


            // Synchronizace s UI
            Dispatcher.BeginInvoke(() => { lstData.ItemsSource = images; });
        }
    }
}
