using System;
using System.Linq;
using System.Security;
using System.Text;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using BeWo.Service.Plugins;
using BS.Shared.DataContracts;
using BS.Shared.Services;

using BeWo.Data;
using BeWo.Data.Access;
using BeWo.Data.Entities;
using BeWo.Service.DCEntityMapper;
using BeWo.Service.ServiceImplementations;

using BS.Shared;
using BS.Shared.Extensions;

using System.Collections.Generic;

namespace Host
{
    public partial class ServiceRecordPage : Page//, ICallbackEventHandler
    {
		//protected bool IsCreateAllowed
		//{
		//	get { return rights != null && rights.Contains(UserRightType.ServiceRecordView_Create); }
		//}

		//protected bool CurrentSCHasGoals { get; set; }

		//private List<UserRightType> rights;
		//private Dictionary<ValueListEntry, List<ValueListEntry>> ziele = new Dictionary<ValueListEntry, List<ValueListEntry>>();

		//private string GetCallbackReference(Control control)
		//{
		//	return Page.ClientScript.GetCallbackEventReference(control, "arg", "callback", "context");
		//}

		//private string SaveTabStateCallbackRaiseEvent(string argument)
		//{ 
		//	Session["CurrentlySelectedTab"] = argument;
		//	return argument;
		//}

		//protected void Page_Load(object sender, EventArgs e)
		//{
		//	try
		//	{
				
		//		if (!SessionFacade.IsUserLoggedIn())
		//			throw new SecurityException("Anmeldung erforderlich!");

		//		var cm = Page.ClientScript;

		//		var cbReference = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "");
		//		var callbackScript = "function CallServer(arg, context) {" + cbReference + "; }";

		//		cm.RegisterClientScriptBlock(GetType(), "CallServer", callbackScript, true);

		//		rights = SessionFacade.LoggedInUser.UserGroups.SelectMany(ug => ug.Rights.Select(r => r.RightType)).ToList();

		//		bt_create.DataBind();

		//		if (IsPostBack) return;

		//		var SelectedSupportConcept = "-1";
		//		if (Session["SelectedSupportConcept"] != null)
		//		{
		//			SelectedSupportConcept = Session["SelectedSupportConcept"].ToString();
		//		}
					
		//		var operationsService = new OperationsServiceImp();

		//		// Browserinformationen speichern
		//		var brauser = Page.Request.Browser;

		//		var brauserInfoDC = new BeWoMobilBrowserInfoDC
		//		{
		//			Type = brauser.Type,
		//			Name = brauser.Browser,
		//			BrowserVersion = brauser.Version,
		//			Platform = brauser.Platform,
		//			Tenant = SessionFacade.Tenant
		//		};
				
		//		operationsService.InsertBeWoMobilBrowserInfo(brauserInfoDC);
		//		// ------------------------
				

		//		var customers = SessionFacade.LoggedInUser.Employee.Employee2CustomerList.Select(ec => ec.Customer).ToList();
		//		var supportConcepts = DAOFactory.SearchDAO.GetAllActiveSupportConceptsByCustomers(customers.Select(s => s.Oid.Value).ToList());

		//		//if (!rights.Contains(UserRightType.ServiceRecord_AllowCreateServiceRecordsForAllClients))
		//		//	supportConcepts = supportConcepts.Where(s => customers.Contains(s.Customer)).ToList();

		//		if(!rights.Contains(UserRightType.ServiceRecordView_View))
		//			supportConcepts.Clear();

		//		foreach (var sc in supportConcepts.OrderBy(sc => sc.Customer.Person.LastName))
		//			foreach (var cb in sc.CostBearer2SupportConceptList)
		//			{
		//				var li = new ListItem(sc.Customer.Person.LastName
		//									  + ", "
		//									  + sc.Customer.Person.FirstName[0]
		//									  + ". "
		//									  + (cb.StartDate.HasValue ? cb.StartDate.Value.ToShortDateString().Remove(6, 2) + "-" : string.Empty)
		//									  + (cb.EndDate.HasValue ? cb.EndDate.Value.ToShortDateString().Remove(6, 2) : string.Empty)
		//									  + " "
		//									  + cb.CostBearer.Organisation.Name, cb.Oid.ToString());

		//				combo_supportconcepts.Items.Add(li);
		//			}

		//		combo_supportconcepts.Items.Insert(0, new ListItem(string.Empty, "-1"));

		//		combo_supportconcepts.SelectedValue = SelectedSupportConcept;

		//		var serviceCategories = operationsService.GetAllServiceCategories();

		//		combo_serviceCategories.Items.AddRange(serviceCategories
		//			.Select(c => new ListItem(c.Name, c.ServiceCategoryOid.ToString())).ToArray());

		//		combo_serviceDescriptions.Items.AddRange(operationsService.GetAllServiceDescriptions()
		//			.Where(sd => sd.Category.ServiceCategoryOid.Equals(serviceCategories[0].ServiceCategoryOid))
		//			.Select(sd => new ListItem(sd.Name, sd.ServiceDescriptionOid.ToString())).ToArray());

					

		//		tb_date.Text = DateTime.Now.ToShortDateString();

		//		if (!SelectedSupportConcept.Equals("-1"))
		//		{
		//			RefreshEntryList();
		//		}

		//		//var allCustomers = DAOFactory.GenericDAO.GetAllActive<Customer>();

		//		//foreach (var li in allCustomers.Select(customer => new ListItem(customer.Person.FirstNameLastName, customer.Oid.ToString())))
		//		//{
		//		//	CustomerDropdownList.Items.Add(li);
		//		//}

		//		//CustomerDropdownList.Items.Insert(0, new ListItem(string.Empty, "-1"));
		//		//CustomerDropdownList.SelectedIndex = 0;
		//	}
		//	catch (Exception ex)
		//	{
		//		lbl_error.Text = "Es ist leider ein Fehler aufgetreten: " + ex.Message;
		//	}
		//}

		//protected void bt_create_Click(object sender, EventArgs e)
		//{
		//	if (rights != null && !rights.Contains(UserRightType.ServiceRecordView_Create)) return;

		//	lbl_error.Text = string.Empty;
		//	lbl_success.Text = string.Empty;
		//	int startHours, startMinutes, endHours, endMinutes, durationMinutes;
		//	DateTime date;

		//	if (combo_supportconcepts.SelectedValue.Equals("-1"))
		//	{
		//		lbl_error.Text = "Bitte wählen Sie einen Hilfeplan aus";
		//		return;
		//	}
	        
		//	if (!DateTime.TryParse(tb_date.Text, out date))
		//	{
		//		lbl_error.Text = "Bitte geben Sie ein gültiges Datum an";
		//		return;
		//	}

		//	var cb2sc = DAOFactory.GenericDAO.LoadByID<CostBearer2SupportConcept>(long.Parse(combo_supportconcepts.SelectedValue));
		//	var sd = DAOFactory.GenericDAO.LoadByID<ServiceDescription>(long.Parse(combo_serviceDescriptions.SelectedValue));

		//	var actualMinuteIntervall = MapperFactory.CostRatePeriodDC_CostRatePeriod
		//												 .MapToNewDCs(cb2sc.CostBearer.CostRatePeriods)
		//												 .GetCurrentlyValidRateValue(CostRatePeriodType.MinutesIntervall) ?? 0m;

		//	var ausgewaehlteZiele = (IList<ValueListEntry2Object>) Session["AusgewaehlteZiele"];
		//	var sr = new ServiceRecord
		//				 {
		//					 Notice = tb_notice.Text,
		//					 SupportConcept = cb2sc.SupportConcept,
		//					 Customer = cb2sc.SupportConcept.Customer,
		//					 CostBearer2SupportConcept = cb2sc,
		//					 CostBearer2SupportConceptOid=cb2sc.Oid,
		//					 Employee = SessionFacade.LoggedInUser.Employee,
		//					 ServiceDescription = sd,
		//					 InsTs = DateTime.Now,
		//					 InsUser = SessionFacade.LoggedInUser.LoginName,
		//					 IP = Request.UserHostAddress,
		//					 ValueList = ausgewaehlteZiele
		//				 };

		//	bool durationParsedSuccessfully = Int32.TryParse(tb_duration.Value, out durationMinutes);
		//	bool startParsedSuccessfully = TryParseTime(tb_start.Value, out startHours, out startMinutes);
		//	bool endParsedSuccessfully = TryParseTime(tb_stop.Value, out endHours, out endMinutes);

		//	if (!durationParsedSuccessfully || durationMinutes == 0)
		//	{
		//		// keine Dauer angegeben... start & stop
		//		if (startParsedSuccessfully && endParsedSuccessfully)
		//		{
		//			var start = date.AddHours(startHours).AddMinutes(startMinutes);
		//			var stop = date.AddHours(endHours).AddMinutes(endMinutes);

		//			if (start > stop)
		//			{
		//				lbl_error.Text = "Die Startzeit muss vor der Endzeit liegen";
		//				return;
		//			}

		//			sr.Start = start;
		//			sr.End = stop;
		//			var duration = (int)(stop - start).TotalMinutes;
            
		//			if (sr.CostBearer2SupportConcept != null)
		//			{
		//				var calc = PluginLoader.FindClass<Calculations>(sr.CostBearer2SupportConcept.CostBearer.ID) ?? Calculations.GetInstance(sr.CostBearer2SupportConcept.CostBearer.ID);
		//				duration = calc.GetRoundedDuration((int) actualMinuteIntervall, duration);
		//			}
		//			sr.RoundedDuration = duration;
		//		}
		//		else
		//		{
		//			lbl_error.Text = "Bitte geben Sie eine gültige Dauer (in Minuten) oder Start und Endzeit an (HH:MM oder HHMM).";
		//			return;
		//		}
		//	}
		//	else
		//	{
		//		// Dauer angegeben
		//		if (sr.CostBearer2SupportConcept != null)
		//		{
		//			var calc = PluginLoader.FindClass<Calculations>(sr.CostBearer2SupportConcept.CostBearer.ID) ?? Calculations.GetInstance(sr.CostBearer2SupportConcept.CostBearer.ID);
		//			durationMinutes = calc.GetRoundedDuration((int)actualMinuteIntervall, durationMinutes);
		//		}

		//		sr.RoundedDuration = durationMinutes;
                
		//		if (startParsedSuccessfully && (startHours > 0 || startMinutes > 0))
		//		{
		//			// Dauer und Start angegeben
		//			sr.Start = date.AddHours(startHours).AddMinutes(startMinutes);
		//		}
		//		else
		//		{
		//			// nur Dauer, kein Start angegeben
		//			sr.Start = date.AddSeconds(1);
		//		}

		//		sr.End = sr.Start.Value.AddMinutes(durationMinutes);
		//	}

		//	var mandator = new OperationsServiceImp().GetMandatorEntity();
		//	//List<UserRightType> rights = SessionFacade.LoggedInUser.UserGroups.SelectMany(ug => ug.Rights.Select(r => r.RightType)).ToList();

		//	if (!rights.Contains(UserRightType.ServiceRecord_AllowEditAfterMaxDaysInNextMonth) && mandator.MaxDaysEditServiceRecordsAllowed.HasValue && mandator.MaxDaysEditServiceRecordsAllowed.Value > 0)
		//	{
		//		var dt = date.AddMonths(1);
		//		dt = dt.AddDays(mandator.MaxDaysEditServiceRecordsAllowed.Value);
		//		if (DateTime.Now >= dt)
		//		{
		//			lbl_error.Text = "Sie können keine neuen Leistungen für den " + date.ToShortDateString() + " dokumentieren, da bereits der " + mandator.MaxDaysEditServiceRecordsAllowed + ". des nachfolgenden Monats überschritten ist.";
		//			return;
		//		}
		//	}

		//	if (mandator.IsServiceRecordNoticeMandatory && string.IsNullOrEmpty(sr.Notice))
		//	{
		//		lbl_error.Text = "Bitte dokumentieren Sie die erbrachte Leistung (Notiz)";
		//		return;
		//	}

			

		//	DAOFactory.GenericDAO.Insert(sr);
		//	tb_start.Value = tb_stop.Value = tb_notice.Text = tb_duration.Value = string.Empty;
		//	tb_date.Text = DateTime.Now.ToShortDateString();
		//	lbl_success.Text = "Die Leistung wurde erfolgreich gebucht";

		//	RefreshEntryList();
		//}

		//protected void combo_serviceCategories_SelectedIndexChanged(object sender, EventArgs e)
		//{
		//	lbl_success.Text = string.Empty;
		//	var operationsService = new OperationsServiceImp();

		//	combo_serviceDescriptions.Items.Clear();
		//	combo_serviceDescriptions.Items.AddRange(operationsService.GetAllServiceDescriptions()
		//		.Where(sd => sd.Category.ServiceCategoryOid.ToString().Equals(combo_serviceCategories.SelectedValue))
		//		.Select(sd => new ListItem(sd.Name, sd.ServiceDescriptionOid.ToString())).ToArray());
		//}

		//protected void combo_supportconcepts_SelectedIndexChanged(object sender, EventArgs e)
		//{
		//	lbl_success.Text = string.Empty;
		//	Session.Remove("AusgewaehlteZiele");
		//	RefreshEntryList();
		//}

		//private void RefreshEntryList()
		//{
		//	lb_entries.DataSource = null;

		//	if (!combo_supportconcepts.SelectedValue.Equals("-1"))
		//	{
		//		var oid = long.Parse(combo_supportconcepts.SelectedValue);
		//		var list = DAOFactory.SearchDAO.FindServiceRecords(null, oid);

		//		var filteredList = new List<ServiceRecord>();

		//		var groupOids = new Dictionary<long, bool>();
		//		foreach (var item in list)
		//		{
		//			if (item.CostBearer2SupportConceptOid != oid) continue;

		//			if (!item.GroupOid.HasValue || !groupOids.ContainsKey(item.GroupOid.Value))
		//				filteredList.Add(item);
		//			if (item.GroupOid.HasValue && !groupOids.ContainsKey(item.GroupOid.Value))
		//				groupOids.Add(item.GroupOid.Value, true);
		//		}
		//		filteredList.Sort((x, y) => y.Start.Value.CompareTo(x.Start.Value));
		//		lb_entries.DataSource = filteredList;

		//		var sc = DAOFactory.GenericDAO.GetByID<CostBearer2SupportConcept>(oid);
		//		if (sc != null)
		//		{
		//			if (sc.SupportConcept.ValueList.Count > 0)
		//				CurrentSCHasGoals = true;

		//			var children = sc.SupportConcept.ValueList.Where(vl => vl.Entry.Type == ValueListEntryType.SupportConceptGoalCategoryType || vl.Entry.Type == ValueListEntryType.SupportConceptGoalType || vl.Entry.Type == ValueListEntryType.SupportConceptIndividualGoalType).ToList();
		//			var parentOids = sc.SupportConcept.ValueList.Where(el => el.Entry.ParentOid.HasValue).Select(el => el.Entry.ParentOid.Value).ToList();
		//			var parents = DAOFactory.GenericDAO.LoadByIDs<ValueListEntry>(parentOids).Distinct().ToList();

		//			ziele = parents.ToDictionary(parent => parent, parent => children.Where(c => c.Entry.ParentOid.HasValue && parent.Oid.HasValue && c.Entry.ParentOid == parent.Oid.Value).Select(c => c.Entry).ToList());

		//			GoalListView.ItemDataBound += GoalListView_ItemDataBound;
		//			GoalListView.DataSource = ziele;
		//			GoalListView.DataBind();
		//		}
		//	}

		//	lb_entries.DataBind();
		//}

		//private static bool TryParseTime(string text, out int hours, out int minutes)
		//{
		//	try
		//	{
		//		String[] hnm = null;

		//		if (text.IndexOf(":") >= 0)
		//		{
		//			hnm = text.Split(':');
		//		}
		//		else
		//		{
		//			if (text.Length <= 2)
		//			{
		//				hnm = new[] { text, "00" };
		//			}
		//			else if (text.Length == 4)
		//			{
		//				hnm = new[] { text.Substring(0, 2), text.Substring(2) };
		//			}
		//		}

		//		hours = int.Parse(hnm[0]);
		//		minutes = int.Parse(hnm[1]);

		//		return (hours >= 0 && hours <= 23) && (minutes >= 0 && minutes <= 59);
		//	}
		//	catch
		//	{
		//		hours = 0;
		//		minutes = 0;
		//		return false;
		//	}
		//}

		//protected void OnDeleteBtnClick(object sender, EventArgs e)
		//{
		//	if (rights != null && !rights.Contains(UserRightType.ServiceRecordView_Create)) return;

		//	var b = (Button)sender;
		//	var serviceRecordOid = b.CommandArgument;
		//	long oid;
		//	var couldParse = long.TryParse(serviceRecordOid, out oid);

		//	var sr = DAOFactory.GenericDAO.GetByID<ServiceRecord>(oid);
			
		//	if (!couldParse || !sr.Version.HasValue) return;

		//	var operationsService = new OperationsServiceImp();
		//	operationsService.DeleteServiceRecord(oid, sr.Version.Value);

		//	RefreshEntryList();

		//	lbl_success.Text = "Der Eintrag '" + sr.Title + "' wurde erfolgreich gelöscht";
		//}

		//protected void OnEditBtnClick(object sender, EventArgs e)
		//{
		//	if (rights != null && !rights.Contains(UserRightType.ServiceRecordView_Edit)) return;

		//	var b = (Button) sender;
		//	var serviceRecordOid = b.CommandArgument;
		//	long oid;
		//	var couldParse = long.TryParse(serviceRecordOid, out oid);

		//	if (!couldParse) return;

		//	var cb2sc = DAOFactory.GenericDAO.LoadByID<CostBearer2SupportConcept>(long.Parse(combo_supportconcepts.SelectedValue));

		//	Session["ServiceRecord2Edit"] = DAOFactory.GenericDAO.GetByID<ServiceRecord>(oid);
		//	Session["actualMinuteIntervall"] = MapperFactory.CostRatePeriodDC_CostRatePeriod
		//												 .MapToNewDCs(cb2sc.CostBearer.CostRatePeriods)
		//												 .GetCurrentlyValidRateValue(CostRatePeriodType.MinutesIntervall) ?? 0m;

		//	Response.Redirect("~/ServiceRecordEditPage.aspx?tenant=" + SessionFacade.Tenant);
		//}

		//protected bool IsEditBtnVisible()
		//{
		//	return rights != null && rights.Contains(UserRightType.ServiceRecordView_Edit);
		//}

		//protected bool IsDelBtnVisible()
		//{
		//	return rights != null && rights.Contains(UserRightType.ServiceRecordView_Delete);
		//}

		//private void GoalListView_ItemDataBound(object sender, ListViewItemEventArgs e)
		//{
		//	try
		//	{
		//		var dataItem = (ListViewDataItem)e.Item;
		//		var objList = (KeyValuePair<ValueListEntry, List<ValueListEntry>>)dataItem.DataItem;

		//		var ddlListOfObjs = (ListView)dataItem.FindControl("GoalsThemselvesListView");
		//		ddlListOfObjs.DataSource = objList.Value;
		//		ddlListOfObjs.DataBind();
		//	}
		//	catch (Exception ex)
		//	{
		//		lbl_error.Text = "Es ist ein Fehler bei der Zieleauflistung aufgetreten: " + ex.Message;
		//	}
		//}

		//public void RaiseCallbackEvent(string valueListEntryOid)
		//{
		//	var test = (List<ValueListEntry2Object>) Session["AusgewaehlteZiele"];
		//	if(test == null)
		//		Session["AusgewaehlteZiele"] = new List<ValueListEntry2Object>();

		//	var selectedGoals = (List<ValueListEntry2Object>) Session["AusgewaehlteZiele"];
		//	var oid = Convert.ToInt64(valueListEntryOid);

		//	if (selectedGoals.Any(a => a.Oid == oid)) return;

		//	var sg = DAOFactory.GenericDAO.GetByID<ValueListEntry>(oid);
			
		//	var blah = new ValueListEntry2Object
		//	{
		//		Entry = sg,
		//		InsTs = DateTime.Now,
		//		InsUser = SessionFacade.LoggedInUser.Employee.Person.FirstNameLastName,
		//		IsActive = ActivationTypeId.Active,
		//		ObjectTid = TableID.ServiceRecord
		//	};

		//	selectedGoals.Add(blah);
		//	Session["AusgewaehlteZiele"] = selectedGoals;
		//}

		//public string GetCallbackResult() { return string.Empty; }

		//protected void combo_customers_SelectedIndexChanged(object sender, EventArgs e)
		//{
		    
		//}
    }
}