using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using WikipediaForWord.LiveSearch;

using Word = Microsoft.Office.Interop.Word;
using System.Xml.Linq;
using System.Net;
using System.IO;

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

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

        public WikipediaSearch()
        {
            InitializeComponent();
        }

        private void WikipediaSearch_Load(object sender, RibbonUIEventArgs e)
        {

        }

        private void cmdSearch_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Selection selectedText = Globals.ThisAddIn.Application.Selection;

            string query = String.Format("{0} site:{1}.wikipedia.org", 
                                        Uri.EscapeDataString(selectedText.Text.Trim()),                            
                                        cmbWeb.Text.ToLower());


            string url = String.Format(SEARCH_URL,
                                        APP_ID,
                                        "cs-CZ",
                                        query);

            WebRequest request = WebRequest.Create(new Uri(url));
            WebResponse response = request.GetResponse();
            StreamReader data = new StreamReader(response.GetResponseStream());

            XDocument d = XDocument.Parse(data.ReadToEnd());
            
            XElement resultElement = d.Descendants(web + "WebResult").FirstOrDefault<XElement>();

            if (resultElement == null)
            {
                return;
            }
            
            object missing = System.Reflection.Missing.Value;
            
            object resultUrl = resultElement.Element(web + "Url").Value;
            object resultTitle = resultElement.Element(web + "Title").Value;

            Globals.ThisAddIn.Application.ActiveDocument.Hyperlinks.Add(selectedText.Range,
                                                    ref resultUrl,
                                                    ref missing,
                                                    ref resultTitle,
                                                    ref missing,
                                                    ref missing); 
        }
    }
}
