/*
	$Id: TwitterStatusViewer.cs 61 2010-02-01 17:01:38Z catwalk $
*/
using System;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Reflection;
using System.Web;
using Hiyoko.Net;
using Hiyoko.Net.Twitter;
using Hiyoko.Utilities;

namespace Hiyoko.Forms{
	using WinForms = System.Windows.Forms;
	using Gdi = System.Drawing;
	
	public partial class TwitterStatusViewer : UserControl{
		public TwitterStatusViewer(){
			this.InitializeComponent();
			Program.ThemeManager.Attach(this.Resources);
			this.Unloaded += delegate{
				Program.ThemeManager.Detach(this.Resources);
			};
			this.inlineImagePanel.Children.Add(new Image());
		}
		
		public static readonly DependencyProperty StatusProperty =
			DependencyProperty.Register("Status", typeof(Status), typeof(TwitterStatusViewer), new PropertyMetadata(Status.Empty, TextPropertyChanged));
		public Status Status{
			get{
				return (Status)this.GetValue(StatusProperty);
			}
			set{
				this.SetValue(StatusProperty, value);
			}
		}

		private static void TextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){
			var self = (TwitterStatusViewer)d;
			self.inlineImagePanel.Children.Clear();
			var status = (Status)e.NewValue;
			if(Program.Settings.IsExpandImagesInStatus){
				if(!String.IsNullOrEmpty(status.Text)){
					foreach(var url in status.Text.ExtractUrls()){
						BitmapImage bmp = null;
						var twitpic = Program.Twitpic ?? new Twitpic();
						bmp = twitpic.GetThumbnail(url, false);
						if(bmp == null){
							bmp = new BitmapImage(new Uri(url));
						}
						if(bmp != null){
							double scaleW = ((bmp.Width > 0) && (bmp.Width > 240)) ? (240 / bmp.Width) : 1.0;
							double scaleH = ((bmp.Height > 0) && (bmp.Height > 240)) ? (240 / bmp.Height) : 1.0;
							double scale = Math.Min(scaleW, scaleH);
							var image = new Image();
							image.Source = bmp;
							image.Width = bmp.Width * scale;
							image.Height = bmp.Height * scale;
							bmp.DownloadCompleted += delegate{
								scaleW = ((bmp.Width > 0) && (bmp.Width > 240)) ? (240 / bmp.Width) : 1.0;
								scaleH = ((bmp.Height > 0) && (bmp.Height > 240)) ? (240 / bmp.Height) : 1.0;
								scale = Math.Min(scaleW, scaleH);
								image.Width = bmp.Width * scale;
								image.Height = bmp.Height * scale;
							};
							bmp.DownloadFailed += delegate{
								self.inlineImagePanel.Children.Remove(image);
							};
							self.inlineImagePanel.Children.Add(image);
						}
					}
				}
			}
		}
	}
}