using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Xml.Linq;

namespace RssReader
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Dictionary<string, RssItem> items
            = new Dictionary<string, RssItem>();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string url = "";

            #region 设置RSS访问位置
            switch (comboBox1.SelectedIndex)
            {
                case 0:
                    url = "http://tw.news.yahoo.com/rss/life";
                    break;
                case 1:
                    url = "http://udn.com/udnrss/latest.xml";
                    break;
                default:
                    url = "http://tw.news.yahoo.com/rss/life";
                    break;
            }
            #endregion

            try
            {
                //TODO: 1.加载RSS新闻数据
                XElement rssData = XElement.Load(url);

                listBox1.Items.Clear();
                items.Clear();

                //TODO: 2.取出新闻标题，转成RssItem对象，并暂存到列表控件中
                var itemQuery =
                    from item in rssData.Descendants(XName.Get("item"))
                    select new
                    {
                        Guid = item.Element(XName.Get("guid")).Value,
                        Title = item.Element(XName.Get("title")).Value,
                        Link = item.Element(XName.Get("link")).Value
                    };
                ListBoxItem listItem;
                foreach (var result in itemQuery)
                {
                    listItem = new ListBoxItem();
                    listItem.Content = result.Title;
                    listItem.Tag = new RssItem(result.Guid, result.Title, result.Link);
                    listBox1.Items.Add(listItem);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("新闻标题更新失败! 请检查是否已连接到因特网!");
            }

        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listBox1.SelectedIndex != -1)
            {
                //TODO: 3.取出调用选取项目，显示新闻内容
                ListBoxItem selectedItem = listBox1.SelectedItem as ListBoxItem;
                RssItem item = selectedItem.Tag as RssItem;
                webBrowser1.Navigate(item.Link);
            }
        }
    }
}

