﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using Telerik.Windows.Data;
using Telerik.Windows.Controls.GridView;

namespace Telerik.Windows.Controls
{
	public class GridViewDynamicHyperlinkColumn : GridViewBoundColumnBase
	{
		/// <summary>
		/// Determines whether the data represented by the column can be edited.
		/// </summary>
		/// <returns>
		/// 	<c>true</c> if the data represented by the column can be edited; otherwise, <c>false</c>.
		/// </returns>
		public override bool CanEdit(object item)
		{
			return false;
		}

		/// <summary>
		///Copy properties from source column.
		/// </summary>
		public override void CopyPropertiesFrom(GridViewColumn source)
		{
			base.CopyPropertiesFrom(source);

			var column = source as GridViewDynamicHyperlinkColumn;
			if (column != null)
			{
				this.NavigateUrlMemberPaths = column.NavigateUrlMemberPaths;
				this.NavigateUrlFormatString = column.NavigateUrlFormatString;
				this.TargetName = column.TargetName;
			}
		}

		/// <summary>
		/// Creates the element for the cell in view mode.
		/// </summary>
		public override FrameworkElement CreateCellElement(Telerik.Windows.Controls.GridView.GridViewCell cell, object dataItem)
		{
			var element = base.CreateCellElement(cell, dataItem);

			HyperlinkButton link = new HyperlinkButton();
			cell.Content = link;
			if (cell.ParentDataControl != null)
			{
				StyleManager.SetTheme(link, StyleManager.GetTheme(cell.ParentDataControl));
			}

			link.Content = element;

			#if SILVERLIGHT4 || SILVERLIGHT5
			link.IsTabStop = false;
			#endif
			link.TargetName = this.TargetName;

			if (!String.IsNullOrEmpty(NavigateUrlMemberPaths) &&
				!String.IsNullOrEmpty(NavigateUrlFormatString))
			{
				var names = NavigateUrlMemberPaths.Split(',');
				var values = new List<object>();
				foreach (var name in names)
				{
					if (dataItem != null)
					{
						values.Add(ObjectDataBinder.GetValue(dataItem, name.Trim()));
					}
				}
				if (values.Count > 0)
				{
					link.NavigateUri = new Uri(String.Format(NavigateUrlFormatString, values.ToArray()), UriKind.RelativeOrAbsolute);
				}
			}

			return link.RemoveErrorTemplate();
		}

		/// <summary> 
		/// Gets or sets comma separated field names. 
		/// </summary> 
		public string NavigateUrlMemberPaths{get;set;}

		/// <summary> 
		/// Gets or sets url string format. 
		/// </summary> 
		public string NavigateUrlFormatString{get;set;}

		/// <summary> 
		/// Gets or sets target name for the hyperlink. 
		/// </summary> 
		public string TargetName{get;set;}
	}
}
