using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
using System.Reflection;
using System.Configuration;


[System.Web.Script.Services.ScriptService]
public class UserWebService : WebService
{
	public class ViewManager
	{
		public static string RenderView(string path)
		{
			return RenderView(path, null);
		}

		public static string RenderView(string path, object data)
		{
			Page pageHolder = new Page();
			UserControl viewControl = (UserControl)pageHolder.LoadControl(path);

			if (data != null)
			{
				Type viewControlType = viewControl.GetType();
				FieldInfo field = viewControlType.GetField("Data");

				if (field != null)
				{
					field.SetValue(viewControl, data);
				}
				else
				{
					throw new Exception("View file: " + path + " does not have a public Data property");
				}
			}

			pageHolder.Controls.Add(viewControl);

			StringWriter output = new StringWriter();
			HttpContext.Current.Server.Execute(pageHolder, output, false);

			return output.ToString();
		}
	}
	[WebMethod]
	public string GetUserDetails(object context)
	{
		IDictionary<string, object> contextDictionary = (IDictionary<string, object>)context;
		string userID = ((string)contextDictionary["TargetControlID"]);

		DataTable userDetails = UserWebService.DB_GetDataTable(userID);

		string path = "~/UserControls/";

		return ViewManager.RenderView(path + "UserDetails.ascx", userDetails);
	}
	
	static DataTable DB_GetDataTable(string key)
	{
		DataTable information = new DataTable();
		string connstr = ConfigurationManager.ConnectionStrings["HelpDesk2ConnectionString"].ConnectionString;

		SqlConnection dbCon = new SqlConnection(connstr);

		dbCon.Open();
		SqlDataAdapter adapter = new SqlDataAdapter();
		string strSelect = " SELECT * FROM [Users] WHERE UserID=@id";
		try
		{
			adapter.SelectCommand = new SqlCommand(strSelect, dbCon);
			adapter.SelectCommand.Parameters.AddWithValue("@id", key);
			adapter.Fill(information);
		}
		finally
		{
			if (!Object.Equals(adapter.SelectCommand, null)) adapter.SelectCommand.Dispose();
			if (dbCon.State == ConnectionState.Open)
			{
				dbCon.Close();
			}
		}
		return information;
	}


}

