using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using BeWo.Data.Entities;
using BeWoPlanerMobil.Models;
using BeWoPlanerMobil.Service;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;

using Newtonsoft.Json;

namespace BeWoPlanerMobil.Controllers
{
    public class MainController : AbstractBaseController
    {
        private MainModel model;
        public MainModel Model
        {
            get
            {
                if (!MobileSessionFacade.IsUserLoggedIn())
                {
                    RedirectToActionPermanent("Index", "Login");
                    return null;
                }

                if (Session[MainModelSessionKey] == null || ((MainModel)Session[MainModelSessionKey]).Employee == null)
                {
                    model = new MainModel { Employee = MobileSessionFacade.LoggedInEmployee };
                    Session[MainModelSessionKey] = model;
                }
                else
                {
                    model = (MainModel)Session[MainModelSessionKey];
                }

                return model;
            }
        }

        private const String MainModelSessionKey = "MainModel";

        private Dictionary<long, ValueListEntryDC> ParentGoals;

        private static readonly List<ValueListEntryType> ZIELTYPEN = new List<ValueListEntryType> { ValueListEntryType.SupportConceptGoalCategoryType, ValueListEntryType.SupportConceptIndividualGoalCategoryType };
        private static readonly List<ValueListEntryType> MASSNAHMENTYPEN = new List<ValueListEntryType> { ValueListEntryType.SupportConceptGoalType, ValueListEntryType.SupportConceptIndividualGoalType };

        [Authorize]
        public ActionResult Main()
        {
            try
            {
                ViewData["ValidationError"] = String.Empty;

                if (!MobileSessionFacade.IsUserLoggedIn())
                    return RedirectToActionPermanent("Index", "Login");

                if (MainModel.AllEmployees == null)
                {
                    MainModel.AllEmployees = EmployeeService.GetAllActiveEmployeesCompact();
                }

                var m = Model;
                var myRelatedCustomers = Model.Employee == null ? new List<CustomerEmployeeRelationDC>() : Model.Employee.RelatedCustomers;

                if (MobileSessionFacade.CheckForUserRight(UserRightType.CustomerView_View))
                {
                    Model.Customers = CustomerService.GetAllActiveCustomers().OrderBy(k => k.LastName).ToList();
                }
                else if (MobileSessionFacade.CheckForUserRight(UserRightType.Customer_ViewMyCustomers))
                {
                    Model.Customers = CustomerService.GetActiveCustomersById(myRelatedCustomers.Select(c => c.Customer.CustomerOid).ToList()).OrderBy(k => k.LastName).ToList();
                }
                else
                {
                    Model.Customers = new List<CustomerDC>();
                }

                if (MobileSessionFacade.CheckForUserRight(UserRightType.ServiceRecord_AllowCreationForOtherEmployees))
                {
                    Model.Employees = EmployeeService.GetAllActiveEmployeesCompact();
                }
                else if (MobileSessionFacade.CheckForUserRight(UserRightType.ServiceRecord_AllowCreationForOtherTeamMember) && Model.Employee != null && Model.Employee.EmployeeOid != null)
                {
                    Model.Employees = EmployeeService.GetAllTeamMember(MobileSessionFacade.LoggedInCompactEmployee);
                }
                else
                {
                    Model.Employees = new List<CompactEmployeeDC> { MobileSessionFacade.LoggedInCompactEmployee };
                }

                if (Model.ShowOnlyOwnSupportConcepts == false && MobileSessionFacade.CheckForUserRight(UserRightType.SupportConcept_ViewAllSupportConcepts))
                {
                    Model.SupportConcepts = CustomerService.GetAllActiveSupportConcepts();
                }
                else
                {
                    Model.SupportConcepts = CustomerService.GetAllActiveSupportConceptsByCustomers(Model.Customers.Select(c => c.CustomerOid != null ? c.CustomerOid.Value : 0));
                }

				if (Model.ServiceCategories == null)
				{
					Model.ServiceCategories = new List<ServiceCategoryModel>();
				}

                if (Model.CostBearer2SupportConceptOid != null)
                {
                    LoadRecordsToModel();
                }
            }
            catch (Exception e)
            {
                log.Error(e.Message, e);
            }

            return View(Model);
        }

        [HttpPost]
        [Authorize]
        public ActionResult SetShowOnlyOwnSupportConcepts(FormCollection collection)
        {
            Model.ShowOnlyOwnSupportConcepts = "true,false" == collection["ShowOnlyOwnSupportConcepts"];

            return RedirectToActionPermanent("Main");
        }

        [HttpPost]
        public new ActionResult Logout()
        {
            return base.Logout();
        }

        [Authorize]
        public String LoadGoals(long pCostbearer2SupportConceptOid)
        {
            if (Model == null)
            {
                return "SessionTimeout";
            }

            var sc = Model.SupportConcepts.FirstOrDefault(f => f.CostBearerRelations.Any(cbr => cbr.CostBearer2SupportConceptOid.HasValue && cbr.CostBearer2SupportConceptOid.Value.Equals(pCostbearer2SupportConceptOid)));

            if (sc == null)
                return String.Empty;

            Model.SelectedSupportConcept = sc;

            var selectedGoals = sc.Goals;
            var missingParents = selectedGoals.Where(w => w.ParentOid != null && false == selectedGoals.Any(a => a.ValueListEntryOid.Equals(w.ParentOid))).Select(s => s.ParentOid).ToList();

            ParentGoals = new Dictionary<long, ValueListEntryDC>();
            foreach (var oid in missingParents)
            {
                LoadMissingParents(oid.Value);
            }

            return SerializeObject(BuildGoalTree(selectedGoals.Union(ParentGoals.Values).ToList()));
        }

        private static List<GoalTreeItem> BuildGoalTree(List<ValueListEntryDC> goals)
        {
            var ziele = goals.Where(w => ZIELTYPEN.Contains(w.Type)).OrderBy(s => s.TypeDescription).ToList();
            var massnahmen = goals.Where(w => MASSNAHMENTYPEN.Contains(w.Type)).OrderBy(s => s.TypeDescription).ToList();
            var goalTree = new List<GoalTreeItem>();
            var goalTreeDic = new Dictionary<long, GoalTreeItem>();

            
            foreach (var ziel in ziele)
            {
                var treeItem = new GoalTreeItem {Children = new List<GoalTreeItem>(), Header = ziel.TypeDescription, ParentOid = ziel.ParentOid, ValueListEntryOid = ziel.ValueListEntryOid};

				goalTreeDic.Add(ziel.ValueListEntryOid.Value, treeItem);

                if (ziel.ParentOid == null)
                {
                    goalTree.Add(treeItem);
                }
            }

            foreach (var zielMitEltern in goalTreeDic.Values.Where(w => w.ParentOid != null))
            {
                goalTreeDic[zielMitEltern.ParentOid.Value].Children.Add(zielMitEltern);
            }

            foreach (var ziel in massnahmen)
            {
                var kind = new GoalTreeItem {Children = new List<GoalTreeItem>(), Header = ziel.TypeDescription, IsLeaf = true, ValueListEntryOid = ziel.ValueListEntryOid};

                if (ziel.ParentOid != null && goalTreeDic.ContainsKey(ziel.ParentOid.Value))
                {
                    kind.ParentOid = goalTreeDic[ziel.ParentOid.Value].ParentOid;
                    goalTreeDic[ziel.ParentOid.Value].Children.Add(kind);
                }
            }

			foreach (var item in goalTreeDic.Values)
			{
				if (item.Children.Count == 0 && item.ParentOid.HasValue)
					item.IsLeaf = true;
			}

            return goalTree;
        }

        private void LoadMissingParents(long pParentOid)
        {
            while (true)
            {
                var parentDC = ValueListService.GetValueListEntryByOid(pParentOid);

                if (!ParentGoals.ContainsKey(parentDC.ValueListEntryOid.Value))
                {
                    ParentGoals.Add(parentDC.ValueListEntryOid.Value, parentDC);

                    if (parentDC.ParentOid != null)
                    {
                        pParentOid = parentDC.ParentOid.Value;
                        continue;
                    }
                }

                break;
            }
        }

        public string LoadBWPSettings()
        {
            int x = 0;

            var m = OperationsService.GetMandator();
            var time = GetSettingValue(m.Settings, "TimeUntilUILock");
	        
            return SerializeObject(time);
        }


        public string CheckEndDate() {

            var m = OperationsService.GetMandator();
            var endtime = GetSettingValue(m.Settings, "IsEndDateVisible");

            return SerializeObject(endtime);
        }


        public string CheckDokuReiter() {

            var dokutypes = ValueListService.GetAllValueListEntrysByType(ValueListEntryType.DocumentType);

            return SerializeObject(dokutypes);
        }


        private static string GetSettingValue(string settings, string key)
        {
            if (!String.IsNullOrEmpty(settings))
            {
                if (settings.IndexOf(";") == -1 && settings.IndexOf("=") == -1)
                {
                    return settings;
                }

                string[] keyValuePairs = settings.Split(';');

                return (from pair in keyValuePairs select pair.Split('=') into keyValuePair where keyValuePair.Length == 2 where keyValuePair[0] == key select keyValuePair[1]).FirstOrDefault();
            }

            return null;
        }

        [Authorize]
        public String LoadKalender(String newtoday)
        {
            try
            {
                if (Model == null)
                {
                    return "SessionTimeout";
                }

                var date = DateTime.ParseExact(newtoday, "dd.MM.yyyy", null);

                var parents = KalenderService.GetAllActiveAppointmentsForEmployeeInInterval2(date.Date, date.Date.AddDays(1), Model.Employee.EmployeeOid.Value, MobileSessionFacade.CheckForUserRight(UserRightType.KalenderMitarbeitertermineAnsehen));

                return SerializeObject(parents);

            }
            catch (Exception e)
            {
				log.Error(e.Message, e);
                return SerializeObject("Fehler 510");
            }
        }

       
        public string LoadStatistics(long oid)
        {
            try
            {
                if (Model == null)
                {
                    return "SessionTimeout";
                }

                var parents = OperationsService.CreateSupportConceptStatistics(oid,DateTime.Now); 

                return SerializeObject(parents);
            }
            catch (Exception e)
            {
				log.Error(e.Message, e);
                return SerializeObject("Fehler 560");
            }
        }
       

        public void UpdateKalender(long oid, string betreff, string notice, string startZeit, string endZeit, string day)
        {
            try
            {
                if (Model == null)
                {
                    SerializeObject("SessionTimeout");
                }

                //var date = DateTime.Parse(zeitstempel);
                var date = DateTime.Parse(day);
                var zeit = ConvertRecordTimes(startZeit, endZeit, date, 0);


                var b1 = KalenderService.GetSchedulerAppointmentByid(oid);

                b1.EndDate = zeit[1];
                b1.StartDate = zeit[0];
                b1.Subject = betreff;
                b1.Description = notice;

                KalenderService.UpdateSchedulerAppointments(new List<SchedulerAppointmentDC>{b1});
            }
            catch (Exception e)
            {
				log.Error(e.Message, e);
                SerializeObject("Fehler 550: Internal Server Error");
            }
        }

        public void SaveKalender(String day, String startZeit, String endZeit, String betreff, String notice)
        {
            try
            {
                if (Model == null)
                {
                    SerializeObject("SessionTimeout");
                }

                var date = DateTime.Parse(day);
                var zeit = ConvertRecordTimes(startZeit, endZeit, date, 0);
                var a1 = new List<SchedulerAppointmentDC> {
                    new SchedulerAppointmentDC
                    {
                        EmployeeList = new List<Employee2SchedulerAppointmentDC>(), 
                        CustomerList = new List<CompactCustomerDC>(), 
                        ResourceList = new List<ResourceDC>(), 
                        EndDate      = zeit[1],
                        StartDate    = zeit[0],
                        Subject      = betreff,
                        Description  = notice,
                        Originator   = MobileSessionFacade.LoggedInCompactEmployee
                    }
                };

                KalenderService.InsertSchedulerAppointments(a1);
            }
            catch (Exception e)
            {
				log.Error(e.Message, e);
                SerializeObject("Fehler 520");
            }
        }

        [Authorize]
        public string LoadKalenderTask(String newtoday)
        {
            try
            {
                if (Model == null)
                {
                    return "SessionTimeout";
                }

                var date = DateTime.ParseExact(newtoday, "dd.MM.yyyy", null);

                var tasks = AnalysisService.GetTasksForEmployeeByDate(Model.Employee.EmployeeOid.Value, date);

                return SerializeObject(tasks);
            }

            catch (Exception e)
            {
				log.Error(e.Message, e);
                return SerializeObject("Fehler 530");
            }
        }

        [Authorize]
        public void SaveUnterschrift(String breitengrad, String langengrad, String blob, String zeitstempel, long? ServiceRecord)
        {
            try
            {
                if (Model == null)
                {
                    SerializeObject("SessionTimeout");
                }

                var date = DateTime.Parse(zeitstempel);

                OperationsService.InsertSignature(new SignatureDC
                {
                    DataBild = blob,
                    Latitute = breitengrad,
                    Longitute = langengrad,
                    Zeitstempel = date,
                    ServiceRecordOid = ServiceRecord
                });
            }
            catch (Exception e)
            {
				log.Error(e.Message, e);
                SerializeObject("Fehler 540");
            }
        }

        public void SaveSchalter(bool schalti)
        {
            try
            {
                if (Model == null)
                {
                    SerializeObject("SessionTimeout");
                }
                else
                {
                    Model.Schalter = schalti;
                }
            }
            catch (Exception e)
            {
				log.Error(e.Message, e);
                SerializeObject("Fehler 777: Fail Error Compilation");
            }
        }


		public string LoadServiceCategories(long pServiceCategoryOid)
	    {
			if (Model != null)
			{
				var scm = Model.ServiceCategories.FirstOrDefault(s => s.ServiceCategoryOid.Value == pServiceCategoryOid);
				if (scm != null)
				{
					return SerializeObject(scm.ServiceDescriptions);
				}
			}
			return SerializeObject(new List<ServiceDescriptionDC>());
	    }
        

        // ajax call zur anzeige ob beim nach saven ein fehler aufgetreten ist.
	    public void ErrorZeiterfassungAnzeigen(int errorwert)
	    {
		    try
		    {
			    if (Model == null)
			    {
				    SerializeObject("SessionTimeout");
			    }
			    else
			    {
				    Model.ErrorWert = errorwert;
			    }
		    }
		    catch (Exception e)
		    {
				log.Error(e.Message, e);
			    SerializeObject("Fehler 777: Fail Error Compilation");
		    }
	    }

	    [HttpPost]
        [Authorize]
        public ActionResult CreateServiceRecord(FormCollection collection)
        {
            try
            {
                if (Model == null)
                {
                    return RedirectToActionPermanent("Index", "Login");
                }

				log.Info(string.Format("CreateServiceRecord: datum:{0}; start:{1}; ende:{2}; dauer:{3}; doku:{4}; aktion:{5}", collection["Datum"], collection["Start"], collection["Ende"], collection["Dauer"], collection["Dokumentation"], collection["versteckt"]));


                if (String.IsNullOrEmpty(collection["Datum"]))
                {
                    return View("Main", Model);
                }

                var submitBtnVal = collection["versteckt"];
                var selectedCostbearerSCRelOid = Model.CostBearer2SupportConceptOid < 1 ? null : Model.CostBearer2SupportConceptOid;
                var datum = Convert.ToDateTime(collection["Datum"]);

                DateTime enddatum;

                if (collection["EndDatum"] != "")
                {
                    enddatum = Convert.ToDateTime(collection["EndDatum"]);
                }
                else
                {
                    enddatum = datum;
                }

                var start = collection["Start"];
                var ende = collection["Ende"];
                var dauer = 0;

                if (datum > enddatum) {
                    enddatum = datum;
                }


                if (!String.IsNullOrEmpty(collection["Dauer"]))
                {
                    Int32.TryParse(collection["Dauer"], out dauer);
                }

                var doku = collection["Dokumentation"];
                var doku2 = collection["Dokumentation2"];
                var doku3 = collection["Dokumentation3"];
                var doku4 = collection["Dokumentation4"];
                var doku5 = collection["Dokumentation5"];

                if(doku == "")
                    doku = collection["Dokumentation6"];

                var zeitenFeld = new DateTime[2];

                if (start == String.Empty && ende == String.Empty)
                {
                    zeitenFeld[0] = new DateTime(datum.Year, datum.Month, datum.Day, 0, 0, 1);

                    if(enddatum == datum)
                        zeitenFeld[1] = new DateTime(datum.Year, datum.Month, datum.Day, 0, 0, 1).AddMinutes(dauer);
                    else
                        zeitenFeld[1] = new DateTime(enddatum.Year, enddatum.Month, enddatum.Day, 0, 0, 1).AddMinutes(dauer);
                    
                }
                else
                {
                    if (enddatum == datum)
                        zeitenFeld = ConvertRecordTimes(start, ende, datum, dauer);
                    else {
                        zeitenFeld = ConvertRecordTimesWithEndDate(start, ende, datum, enddatum, dauer);
                    }

                }

                if (dauer == 0 || zeitenFeld[1] != zeitenFeld[0])
                {
                    dauer = (int)(zeitenFeld[1] - zeitenFeld[0]).TotalMinutes;
                }

                if (submitBtnVal.Equals("Speichern"))
                {
                    var selectedRecordOid = Model.SelectedServiceRecordOid;
                    Model.NewServiceRecord = OperationsService.GetServiceRecordById(selectedRecordOid.Value);
                }

                if (Model.NewServiceRecord == null)
                {
                    return RedirectToActionPermanent("Main");
                }

                Model.NewServiceRecord.Goals = Model.SelectedGoals;
                Model.NewServiceRecord.Start = zeitenFeld[0];
                Model.NewServiceRecord.End = zeitenFeld[1];

                if (Model.Employee.EmployeeOid != null)
                {
                    if (!submitBtnVal.Equals("Speichern"))
                    {
                        Model.NewServiceRecord.Employee = Model.SelectedEmployee ?? MobileSessionFacade.LoggedInCompactEmployee;
                    }

                    var sc = Model.SupportConcepts.FirstOrDefault(fod => fod.CostBearerRelations.Any(a => a.CostBearer2SupportConceptOid.HasValue &&
                                                                                                          a.CostBearer2SupportConceptOid.Value.Equals(selectedCostbearerSCRelOid)));
	                if (sc != null)
	                {
		                if (sc.SupportConceptOid != null)
		                {
			                Model.NewServiceRecord.SupportConcept =
				                CustomerService.LoadCompactSupportConceptDC(sc.SupportConceptOid.Value, Model.Employee.EmployeeOid);
		                }

		                Model.NewServiceRecord.Customer = sc.Customer;
		                var cb2ScRel =
			                sc.CostBearerRelations.First(
				                f =>
					                f.CostBearer2SupportConceptOid.HasValue &&
					                f.CostBearer2SupportConceptOid.Equals(selectedCostbearerSCRelOid));
		                Model.NewServiceRecord.CostBearer = cb2ScRel.CostBearer;
		                var intervall = Model.NewServiceRecord.CostBearer.ActualMinuteIntervall;

		                if (intervall > 0)
		                {
			                Model.NewServiceRecord.RoundedDuration = dauer%intervall != 0
				                ? dauer + (intervall - (dauer%intervall))
				                : dauer;
		                }
		                else
		                {
			                Model.NewServiceRecord.RoundedDuration = dauer;
		                }

		                Model.NewServiceRecord.CostBearer2SupportConceptOid = selectedCostbearerSCRelOid;
	                }
	                else
	                {
						Model.NewServiceRecord.RoundedDuration = dauer;
	                }
                }

                Model.NewServiceRecord.Notice = doku;
                
                if(doku2 != "")
                    Model.NewServiceRecord.Notice2 = doku2;
                if (doku3 != "")
                    Model.NewServiceRecord.Notice3 = doku3;
                if (doku4 != "")
                    Model.NewServiceRecord.Notice4 = doku4;
                if (doku5 != "")
                    Model.NewServiceRecord.Notice5 = doku5;
               

                var serviceDescOid = 0L;

                if (Model.SelectedServiceDescriptionOid.HasValue)
                {
                    serviceDescOid = Model.SelectedServiceDescriptionOid.Value;
                }
                else if (!String.IsNullOrEmpty(collection["Leistungen"]))
                {
                    serviceDescOid = Convert.ToInt64(collection["Leistungen"]);
                }

                if (serviceDescOid > 0)
                {
                    Model.NewServiceRecord.ServiceDescription = OperationsService.GetServiceDescription(serviceDescOid);
                }

                if (Model.NewServiceRecord.RoundedDuration == 0)
                    Model.NewServiceRecord.RoundedDuration = dauer;
                
                Model.NewServiceRecord.IP = Request.UserHostAddress;
                Model.NewServiceRecord.InsertedOn = DateTime.Now;
                Model.NewServiceRecord.InsUser = String.Format("{0} {1}", MobileSessionFacade.LoggedInEmployee.FirstName, MobileSessionFacade.LoggedInEmployee.LastName);
                Model.NewServiceRecord.IsCreatedInMobileClient = true;


                List<long> oidList;
                if (submitBtnVal.Equals("Anlegen"))
                {
                    oidList = OperationsService.InsertNewServiceRecords(new List<ServiceRecordDC> { Model.NewServiceRecord });

                    Model.SrviceRecoOID = oidList[0];

                }
                else
                {
                    OperationsService.UpdateServiceRecords(new List<ServiceRecordDC> { Model.NewServiceRecord });
                }

                Model.NewServiceRecord = new ServiceRecordDC();

                if (selectedCostbearerSCRelOid.HasValue)
                {
                    Model.ServiceRecords = OperationsService.FindServiceRecordsForLastDays(selectedCostbearerSCRelOid, Model.Zeitraum, Model.Employee.EmployeeOid).ToList();
                }

            }
            catch (Exception e)
            {
                log.Error(e.Message, e);
            }

            //wenn auf false dann ist Unterschreiben nicht möglich
            Model.Schalter = false;
            model.ButtonsSchalter = false;

            return RedirectToActionPermanent("Main");
        }



        public ActionResult saveZeiterfassungAfterCrash(String Datum, String StartD, String EndeD, String Dauer, String Doku, String Leistungen, String Doku2, String Doku3, String Doku4, String Doku5, String EndDatum)
        {

            try
            {
                if (Model == null)
                {
                    return RedirectToActionPermanent("Index", "Login");
                }

                log.Info(string.Format("saveZeiterfassungAfterCrash: datum:{0};start:{1};ende:{2};dauer:{3};doku:{4};doku2:{5};doku3:{6};doku4:{7};doku5:{8};EndDatum:{9}", Datum, StartD, EndeD, Dauer, Doku, Doku2, Doku3, Doku4, Doku5,EndDatum));


                if (String.IsNullOrEmpty(Datum))
                {
                    return View("Main", Model);
                }

                var selectedCostbearerSCRelOid = Model.CostBearer2SupportConceptOid < 1 ? null : Model.CostBearer2SupportConceptOid;
                var datum = Convert.ToDateTime(Datum);
                var start = StartD;
                var ende = EndeD;
                var dauer = 0;

                DateTime enddatum;

                if (EndDatum != "")
                {
                    enddatum = Convert.ToDateTime(EndDatum);
                }
                else
                {
                    enddatum = datum;
                }

                if (datum > enddatum)
                {
                    enddatum = datum;
                }

                if (!String.IsNullOrEmpty(Dauer))
                {
                    Int32.TryParse(Dauer, out dauer);
                }

                var doku = Doku;
                var doku2 = Doku2;
                var doku3 = Doku3;
                var doku4 = Doku4;
                var doku5 = Doku5;

                var zeitenFeld = new DateTime[2];

                if (start == String.Empty && ende == String.Empty)
                {
                    zeitenFeld[0] = new DateTime(datum.Year, datum.Month, datum.Day, 0, 0, 1);

                    if (enddatum == datum)
                        zeitenFeld[1] = new DateTime(datum.Year, datum.Month, datum.Day, 0, 0, 1).AddMinutes(dauer);
                    else
                        zeitenFeld[1] = new DateTime(enddatum.Year, enddatum.Month, enddatum.Day, 0, 0, 1).AddMinutes(dauer);  
                }
                else
                {
                   if (enddatum == datum)
                        zeitenFeld = ConvertRecordTimes(start, ende, datum, dauer);
                   else 
                        zeitenFeld = ConvertRecordTimesWithEndDate(start, ende, datum, enddatum, dauer);
                }

                if (dauer == 0 || zeitenFeld[1] != zeitenFeld[0])
                {
                    dauer = (int)(zeitenFeld[1] - zeitenFeld[0]).TotalMinutes;
                }

              
                if (Model.NewServiceRecord == null)
                {
                    return RedirectToActionPermanent("Main");
                }

                Model.NewServiceRecord.Goals = Model.SelectedGoals;
                Model.NewServiceRecord.Start = zeitenFeld[0];
                Model.NewServiceRecord.End = zeitenFeld[1];

                if (Model.Employee.EmployeeOid != null)
                {
                        Model.NewServiceRecord.Employee = Model.SelectedEmployee ?? MobileSessionFacade.LoggedInCompactEmployee;
                    
                    var sc = Model.SupportConcepts.FirstOrDefault(fod => fod.CostBearerRelations.Any(a => a.CostBearer2SupportConceptOid.HasValue &&
                                                                                                          a.CostBearer2SupportConceptOid.Value.Equals(selectedCostbearerSCRelOid)));
                    if (sc != null)
                    {
                        if (sc.SupportConceptOid != null)
                        {
                            Model.NewServiceRecord.SupportConcept = CustomerService.LoadCompactSupportConceptDC(sc.SupportConceptOid.Value, Model.Employee.EmployeeOid);
                        }

                        Model.NewServiceRecord.Customer = sc.Customer;
                        var cb2ScRel = sc.CostBearerRelations.First(f => f.CostBearer2SupportConceptOid.HasValue && f.CostBearer2SupportConceptOid.Equals(selectedCostbearerSCRelOid));
                        Model.NewServiceRecord.CostBearer = cb2ScRel.CostBearer;
                        var intervall = Model.NewServiceRecord.CostBearer.ActualMinuteIntervall;

                        if (intervall > 0)
                        {
                            Model.NewServiceRecord.RoundedDuration = dauer % intervall != 0 ? dauer + (intervall - (dauer % intervall)) : dauer;
                        }
                        else
                        {
                            Model.NewServiceRecord.RoundedDuration = dauer;
                        }

                        Model.NewServiceRecord.CostBearer2SupportConceptOid = selectedCostbearerSCRelOid;
                    }
                    else
                    {
                        Model.NewServiceRecord.RoundedDuration = dauer;
                    }
                }

                Model.NewServiceRecord.Notice = doku;

                if (doku2 != "")
                    Model.NewServiceRecord.Notice2 = doku2;
                if (doku3 != "")
                    Model.NewServiceRecord.Notice3 = doku3;
                if (doku4 != "")
                    Model.NewServiceRecord.Notice4 = doku4;
                if (doku5 != "")
                    Model.NewServiceRecord.Notice5 = doku5;


                var serviceDescOid = 0L;

                if (Model.SelectedServiceDescriptionOid.HasValue)
                {
                    serviceDescOid = Model.SelectedServiceDescriptionOid.Value;
                }
                else if (!String.IsNullOrEmpty(Leistungen))
                {
                    serviceDescOid = Convert.ToInt64(Leistungen);
                }

                if (serviceDescOid > 0)
                {
                    Model.NewServiceRecord.ServiceDescription = OperationsService.GetServiceDescription(serviceDescOid);
                }

                Model.NewServiceRecord.IP = Request.UserHostAddress;
                Model.NewServiceRecord.InsertedOn = DateTime.Now;
                Model.NewServiceRecord.InsUser = String.Format("{0} {1}", MobileSessionFacade.LoggedInEmployee.FirstName, MobileSessionFacade.LoggedInEmployee.LastName);
                Model.NewServiceRecord.IsCreatedInMobileClient = true;

                OperationsService.InsertNewServiceRecords(new List<ServiceRecordDC> { Model.NewServiceRecord });

                Model.NewServiceRecord = new ServiceRecordDC();

                if (selectedCostbearerSCRelOid.HasValue)
                {
                    Model.ServiceRecords = OperationsService.FindServiceRecordsForLastDays(selectedCostbearerSCRelOid, Model.Zeitraum, Model.Employee.EmployeeOid).ToList();
                }

            }
            catch (Exception e)
            {
				log.Error(e.Message, e);
                Model.ErrorWert = 2;
                //log.Error(e.Message, e);
            }

            return RedirectToActionPermanent("Main");
        }


        [HttpPost]
        [Authorize]
        public ActionResult SelectSupportConcept(FormCollection formCollection)
        {
            if (Model == null)
            {
                return RedirectToActionPermanent("Index", "Login");
            }

		    long? cb2scOid = Convert.ToInt64(formCollection["CostBearer2SupportConceptOid"]);

		    Model.CostBearer2SupportConceptOid = cb2scOid;
		    Model.SelectedSupportConcept =
			    Model.SupportConcepts.FirstOrDefault(
				    f =>
					    f.CostBearerRelations.Any(
						    a => 
							    a.CostBearer2SupportConceptOid.HasValue &&
							    a.CostBearer2SupportConceptOid.Value.Equals(Model.CostBearer2SupportConceptOid)));

		    if (Model.SelectedSupportConcept != null)
		    {

			    var details =
				    OperationsService.GetSupportConceptTreeNodeDetailInfo(Model.SelectedSupportConcept.Customer.CustomerOid,
					    Model.SelectedSupportConcept.SupportConceptOid, Model.CostBearer2SupportConceptOid);
			    Model.ServiceCategories = details.ServiceAccountings.Count > 0
				    ? CreateServiceCategoryModels(details.ServiceAccountings.Select(sa => sa.ServiceDescription).ToList()) //if
				    : CreateServiceCategoryModels(OperationsService.GetAllServiceDescriptions());                          //else

                Model.ServiceCategories = Model.ServiceCategories.Where(c => !c.OhneHilfeplan.HasValue || c.OhneHilfeplan.Value == AccountingvisibilityType.Beides || c.OhneHilfeplan.Value == AccountingvisibilityType.NurKlientenbezogen).ToList();                 
		    }
		    else if (cb2scOid == -2)
		    {      
			    Model.ServiceCategories = CreateServiceCategoryModels(OperationsService.GetAllServiceDescriptions());
                Model.ServiceCategories = Model.ServiceCategories.Where(c => !c.OhneHilfeplan.HasValue || c.OhneHilfeplan.Value == AccountingvisibilityType.Beides || c.OhneHilfeplan.Value == AccountingvisibilityType.NichtKlientenbezogen).ToList();
		    }
		    else if (cb2scOid == -1)
		    {
			    Model.ServiceCategories.Clear();
		    }

			Model.Zeitraum = 7;
            LoadRecordsToModel();

			return RedirectToActionPermanent("Main");
	    }

	    private List<ServiceCategoryModel> CreateServiceCategoryModels(IList<ServiceDescriptionDC> serviceDescriptions)
	    {
		    var catOid2ModelDict = new Dictionary<long, ServiceCategoryModel>();
		    foreach (var sd in serviceDescriptions)
		    {
			    if (!catOid2ModelDict.ContainsKey(sd.Category.ServiceCategoryOid.Value))
			    {
				    catOid2ModelDict[sd.Category.ServiceCategoryOid.Value] = new ServiceCategoryModel()
				    {
					    Name = sd.Category.Name,
						IsDefault = sd.Category.IsDefault,
					    Percentage = sd.Category.Percentage,
					    Position = sd.Category.Position,
                        OhneHilfeplan = sd.Category.OhneHilfeplan,
					    ServiceCategoryOid = sd.Category.ServiceCategoryOid,
					    ServiceDescriptions = new List<ServiceDescriptionDC>()
				    };
			    }
				catOid2ModelDict[sd.Category.ServiceCategoryOid.Value].ServiceDescriptions.Add(sd);
		    }
			var list = catOid2ModelDict.Values.ToList();
		    list.Sort((s1, s2) =>
		    {
			    if (s1.IsDefault)
				    return 1;
			    if (s1.Position != s2.Position)
				    return s1.Position.CompareTo(s2.Position);
				return s1.ServiceCategoryOid.Value.CompareTo(s2.ServiceCategoryOid.Value);

		    });

		    return list;
	    }

		
        [HttpPost]
        [Authorize]
        public ActionResult DeleteRecord()
        {
            if (Model == null)
            {
                return RedirectToActionPermanent("Index", "Login");
            }

            if (Model.ServiceRecordOidToDelete != null && Model.ServiceRecordOidToDelete > 0 && MobileSessionFacade.LoggedInUser.UserGroups.Any(a => a.Rights.Any(f => f.RightType.Equals(UserRightType.ServiceRecordView_Delete))))
            {
                var serviceRecordDC = Model.ServiceRecords.FirstOrDefault(f => f.ServiceRecordOid != null && f.ServiceRecordOid.Value.Equals(Model.ServiceRecordOidToDelete));
                if (serviceRecordDC != null)
                {
                    var version = serviceRecordDC.ServiceRecordVersion;
                    if (version != null)
                    {
                        OperationsService.DeleteServiceRecord(Model.ServiceRecordOidToDelete.Value, version.Value);

                        Model.ServiceRecords = Model.ServiceRecords.Where(sr => sr.ServiceRecordOid != null && !sr.ServiceRecordOid.Value.Equals(serviceRecordDC.ServiceRecordOid)).ToList();
                    }
                }
            }

            return RedirectToActionPermanent("Main", Model);
        }

        public void SetRecordOidToDelete(long serviceRecordOid)
        {
            if (Model == null)
            {
                RedirectToActionPermanent("Index", "Login");
                return;
            }

            Model.ServiceRecordOidToDelete = serviceRecordOid;
        }

        public void UpdateGoals(long pGoalOid)
        {
            if (Model == null)
            {
                RedirectToActionPermanent("Index", "Login");
                return;
            }

            var sc = Model.SelectedSupportConcept;
            if (sc == null) return;

            var goal = sc.Goals.FirstOrDefault(first => first.ValueListEntryOid.HasValue && first.ValueListEntryOid.Value.Equals(pGoalOid));

            if (Model.SelectedGoals == null)
            {
                Model.SelectedGoals = new List<ValueListEntryDC> { goal };
                return;
            }

            if (Model.SelectedGoals.Contains(goal))
                Model.SelectedGoals.Remove(goal);
            else
                Model.SelectedGoals.Add(goal);
        }

        public class GoalTreeItem
        {
            public String Header { get; set; }
            public bool IsLeaf { get; set; }
            public List<GoalTreeItem> Children { get; set; }
            public long? ParentOid { get; set; }
            public long? ValueListEntryOid { get; set; }
        }

        public void SetServiceDescription(long pServiceDescriptionOid)
        {
            if (Model == null)
            {
                RedirectToActionPermanent("Index", "Login");
                return;
            }

            Model.SelectedServiceDescriptionOid = pServiceDescriptionOid;
        }

        [HttpPost]
        [Authorize]
        public ActionResult LoadServiceRecords(FormCollection formCollection)
        {
            if (Model == null)
            {
                return RedirectToActionPermanent("Index", "Login");
            }

            var zeitraum = int.Parse(formCollection["Records"]);
            if (zeitraum < 0)
                zeitraum = 7;

            Model.Zeitraum = zeitraum;

            LoadRecordsToModel();

            return RedirectToActionPermanent("Main");
        }

        private void LoadRecordsToModel()
        {
            if (Model.Zeitraum < 0 || (Model.CostBearer2SupportConceptOid.HasValue && Model.CostBearer2SupportConceptOid.Value == -1))
            {
                Model.ServiceRecords = new List<ServiceRecordDC>();
                return;
            }

            var records = OperationsService.FindServiceRecordsForLastDays(Model.CostBearer2SupportConceptOid < 1 ? null : Model.CostBearer2SupportConceptOid, Model.Zeitraum, Model.Employee.EmployeeOid);
            var recordsOhneDuplikate = new List<ServiceRecordDC>();

            foreach (var r in records.Where(r => !recordsOhneDuplikate.Any(a => a.GroupOid.HasValue && a.GroupOid.Value.Equals(r.GroupOid))))
            {
                recordsOhneDuplikate.Add(r);
            }

            Model.ServiceRecords = recordsOhneDuplikate;
        }

        public void SetSelectedServiceRecord(long? recordOid)
        {
            if (Model == null)
            {
                RedirectToActionPermanent("Index", "Login");
                return;
            }

            Model.SelectedServiceRecordOid = recordOid;

            if (recordOid == null)
            {
                Model.SelectedGoals = new List<ValueListEntryDC>();
            }
            else
            {
                var serviceRecordDC = Model.ServiceRecords.FirstOrDefault(f => f.ServiceRecordOid.HasValue && f.ServiceRecordOid.Value.Equals(Model.SelectedServiceRecordOid));
                if (serviceRecordDC != null)
                    Model.SelectedGoals = serviceRecordDC.Goals;
            }
        }

        public String GetSelectedRecordInformation()
        {
            var result = String.Empty;

            if (Model.SelectedServiceRecordOid.HasValue)
            {
                result = SerializeObject(Model.ServiceRecords.First(f => f.ServiceRecordOid == Model.SelectedServiceRecordOid));
            }

            return result;
        }

        public String GetSelectedRecordInformationWithOid(long oid)
        {
            var result = String.Empty;
            LoadRecordsToModel();
            result = SerializeObject(Model.ServiceRecords.First(f => f.ServiceRecordOid == oid));

            return result;
        }

        private static String SerializeObject(object obj)
        {
            return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new ShouldSerializeContractResolver(), ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
        }

        private static DateTime[] ConvertRecordTimes(String start, String ende, DateTime datum, int dauer)
        {
            var result = new DateTime[2];
            var startDate = datum;
            var endDate = datum;

            var h = 0;
            var m = 0;

            if (!String.IsNullOrEmpty(start) && (start.Contains(":") || start.Contains(".") || start.Contains(",")))
            {
                var seperator = ':';

                if (start.Contains("."))
                    seperator = '.';
                else if (start.Contains(","))
                    seperator = ',';

                var hm = start.Split(seperator);

                h = Convert.ToInt32(hm[0]);
                m = Convert.ToInt32(hm[1]);
            }
            else if (!String.IsNullOrEmpty(start))
            {
	            if (start.Length <= 2)
	            {
		            m = 0;
		            h = Convert.ToInt32(start);
	            }
	            else
	            {
					m = Convert.ToInt32(start.Substring(start.Length - 2, 2));
					h = Convert.ToInt32(start.Substring(0, start.Length - 2));    
	            }
                
            }

            startDate = startDate.AddHours(h);
            startDate = startDate.AddMinutes(m);

            if (!String.IsNullOrEmpty(ende) && (ende.Contains(":") || ende.Contains(".") || ende.Contains(",")))
            {
                var seperator2 = ':';

                if (ende.Contains("."))
                    seperator2 = '.';
                else if (ende.Contains(","))
                    seperator2 = ',';

                var hm = ende.Split(seperator2);

                h = Convert.ToInt32(hm[0]);
                m = Convert.ToInt32(hm[1]);
            }
            else if (!String.IsNullOrEmpty(ende))
            {
                m = Convert.ToInt32(ende.Substring(ende.Length - 2, 2));
                h = Convert.ToInt32(ende.Substring(0, ende.Length - 2));
            }

            endDate = endDate.AddHours(h);
            endDate = endDate.AddMinutes(m);


            if (String.IsNullOrEmpty(start) && !String.IsNullOrEmpty(ende))
            {
                startDate = endDate.AddMinutes(-1 * dauer);
            }

            if (String.IsNullOrEmpty(ende) && !String.IsNullOrEmpty(start))
            {
                endDate = startDate.AddMinutes(dauer);
            }

            if (endDate < startDate)
            {
                endDate = startDate;
            }

            if (dauer == 0 || endDate == startDate)
            {
                dauer = (int)(endDate - startDate).TotalMinutes;
            }

            result[0] = startDate;
            result[1] = endDate;

            return result;
        }


        private static DateTime[] ConvertRecordTimesWithEndDate(String start, String ende, DateTime datum,DateTime enddatum ,int dauer)
        {
            var result = new DateTime[2];
            var startDate = datum;
            var endDate = enddatum;

            var h = 0;
            var m = 0;

            if (!String.IsNullOrEmpty(start) && (start.Contains(":") || start.Contains(".") || start.Contains(",")))
            {
                var seperator = ':';

                if (start.Contains("."))
                    seperator = '.';
                else if (start.Contains(","))
                    seperator = ',';

                var hm = start.Split(seperator);

                h = Convert.ToInt32(hm[0]);
                m = Convert.ToInt32(hm[1]);
            }
            else if (!String.IsNullOrEmpty(start))
            {
                m = Convert.ToInt32(start.Substring(start.Length - 2, 2));
                h = Convert.ToInt32(start.Substring(0, start.Length - 2));
            }

            startDate = startDate.AddHours(h);
            startDate = startDate.AddMinutes(m);

            if (!String.IsNullOrEmpty(ende) && (ende.Contains(":") || ende.Contains(".") || ende.Contains(",")))
            {
                var seperator2 = ':';

                if (ende.Contains("."))
                    seperator2 = '.';
                else if (ende.Contains(","))
                    seperator2 = ',';

                var hm = ende.Split(seperator2);

                h = Convert.ToInt32(hm[0]);
                m = Convert.ToInt32(hm[1]);
            }
            else if (!String.IsNullOrEmpty(ende))
            {
                m = Convert.ToInt32(ende.Substring(ende.Length - 2, 2));
                h = Convert.ToInt32(ende.Substring(0, ende.Length - 2));
            }

            endDate = endDate.AddHours(h);
            endDate = endDate.AddMinutes(m);


            if (String.IsNullOrEmpty(start) && !String.IsNullOrEmpty(ende))
            {
                startDate = endDate.AddMinutes(-1 * dauer);
            }

            if (String.IsNullOrEmpty(ende) && !String.IsNullOrEmpty(start))
            {
                endDate = startDate.AddMinutes(dauer);
            }

            if (endDate < startDate)
            {
                endDate = startDate;
            }

            if (dauer == 0 || endDate == startDate)
            {
                dauer = (int)(endDate - startDate).TotalMinutes;
            }
            result[0] = startDate;
            result[1] = endDate;

            return result;
        }

        public String CheckRights(String von, String bis, bool inEditMode, String dateString, String startString, String endString)
        {
            if (Model == null)
            {
                return "SessionTimeout";
            }

            log.Info(String.Format("CheckRights: von:{0};bis:{1};inEditMode:{2};dateString:{3};startString:{4};endString:{5}", von, bis, inEditMode, dateString, startString, endString));

            var date = DateTime.Now.Date;

            var startHoursDt = ConvertTimeStringToDateTime(startString);
            var endHoursDt = ConvertTimeStringToDateTime(endString);

            if (!DateTime.TryParse(dateString, out date))
            {
                date = DateTime.Now.Date;
            }

            var startDt = date.AddHours(startHoursDt.Hour).AddMinutes(startHoursDt.Minute);
            var endDt = date.AddHours(endHoursDt.Hour).AddMinutes(endHoursDt.Minute);

            if (startDt > endDt)
            {
                return "StartGreaterEnd";
            }
            var dauer = (int)(endDt - startDt).TotalMinutes;

            if (dauer == 0)
            {
                startDt = startDt.AddSeconds(1);
                endDt = endDt.AddSeconds(1);
            }

            var checkSR = new ServiceRecordDC();
            if (inEditMode)
            {
                checkSR = Model.ServiceRecords.FirstOrDefault(f => f.ServiceRecordOid.HasValue && f.ServiceRecordOid.Value.Equals(Model.SelectedServiceRecordOid));
            }

            if (checkSR == null)
            {
                checkSR = new ServiceRecordDC();
            }

            checkSR.Goals = Model.SelectedGoals;

            checkSR.Start = startDt;
            checkSR.End = endDt;

            if (Model.Employee.EmployeeOid != null)
            {
                checkSR.Employee = MobileSessionFacade.LoggedInCompactEmployee;
           
                var sc = Model.SupportConcepts.FirstOrDefault(fod => fod.CostBearerRelations.Any(a => a.CostBearer2SupportConceptOid.HasValue && a.CostBearer2SupportConceptOid.Value.Equals(Model.CostBearer2SupportConceptOid)));

                if (sc != null)
                {
                    if (sc.SupportConceptOid != null)
                    {
                        checkSR.SupportConcept = CustomerService.LoadCompactSupportConceptDC(sc.SupportConceptOid.Value, Model.Employee.EmployeeOid);
                    }

                    checkSR.Customer = sc.Customer;
                    var cb2ScRel = sc.CostBearerRelations.First(f => f.CostBearer2SupportConceptOid.HasValue && f.CostBearer2SupportConceptOid.Equals(Model.CostBearer2SupportConceptOid));
                    checkSR.CostBearer = cb2ScRel.CostBearer;
                    var intervall = checkSR.CostBearer.ActualMinuteIntervall;

                    if (intervall > 0)
                    {
                        checkSR.RoundedDuration = dauer % intervall != 0 ? dauer + (intervall - (dauer % intervall)) : dauer;
                    }

                    checkSR.CostBearer2SupportConceptOid = Model.CostBearer2SupportConceptOid;
                }
            }

            checkSR.IP = Request.UserHostAddress;
            checkSR.InsertedOn = DateTime.Now;
            checkSR.InsUser = String.Format("{0} {1}", MobileSessionFacade.LoggedInEmployee.FirstName, MobileSessionFacade.LoggedInEmployee.LastName);

            checkSR.ServiceDescription = OperationsService.GetServiceDescription(Model.SelectedServiceDescriptionOid.Value);

            var man = OperationsService.GetMandator();
            var s = man.Settings ?? String.Empty;
            var einzeln = s.Split(';');
            var g = einzeln.ToList().FirstOrDefault(f => f.Contains("MaxDaysEditServiceRecordsAllowed"));
            var t = g != null ? int.Parse(g.Split('=')[1]) : 0;

            SupportConceptStatisticsDC stats = null;
            if (Model.CostBearer2SupportConceptOid != null && Model.CostBearer2SupportConceptOid > 0)
            {
                stats = OperationsService.CreateSupportConceptStatistics(Model.CostBearer2SupportConceptOid.Value, DateTime.Now);
            }

            var result = OperationsService.ValidateServiceRecordEntry(checkSR, stats, t, false, new List<long> { checkSR.Employee.EmployeeOid });
            var valStruct = new ValidationStruct
            {
                ValidationResults = result,
                Rights = new Dictionary<int, bool>(),
                MaxDaysEditServiceRecordsAllowed = t.ToString()
            };

            valStruct.Rights.Add(0, MobileSessionFacade.LoggedInUser.UserGroups.Any(a => a.Rights.Any(f => f.RightType.Equals(UserRightType.ServiceRecord_AllowCreateOverlappingFLS))));
            valStruct.Rights.Add(1, MobileSessionFacade.LoggedInUser.UserGroups.Any(a => a.Rights.Any(f => f.RightType.Equals(UserRightType.ServiceRecord_AllowCreateMoreFLSThanApproved))));
            valStruct.Rights.Add(2, MobileSessionFacade.LoggedInUser.UserGroups.Any(a => a.Rights.Any(f => f.RightType.Equals(UserRightType.BookServiceRecordAfterSettlementInvoice))));

            Model.NewServiceRecord = new ServiceRecordDC();

            return SerializeObject(valStruct);
        }


        public bool CheckRightsAfterCrash(String von, String bis, bool inEditMode, String dateString, String startString, String endString, long costbearerOId, String leistung)
        {
            if (Model == null)
            {
                return false;
            }
			

			log.Info(String.Format("CheckRightsAfterCrash: von:{0};bis:{1};inEditMode:{2};dateString:{3};startString:{4};endString:{5}", von, bis, inEditMode, dateString, startString, endString));

                var date = DateTime.Now.Date;

                var startHoursDt = ConvertTimeStringToDateTime(startString);
                var endHoursDt = ConvertTimeStringToDateTime(endString);

                if (!DateTime.TryParse(dateString, out date))
                {
                    date = DateTime.Now.Date;
                }

                var startDt = date.AddHours(startHoursDt.Hour).AddMinutes(startHoursDt.Minute);
                var endDt = date.AddHours(endHoursDt.Hour).AddMinutes(endHoursDt.Minute);

                if (startDt > endDt)
                {
                    Model.ErrorWert = 5;
                    return false;
                }
                var dauer = (int)(endDt - startDt).TotalMinutes;

                if (dauer == 0)
                {
                    startDt = startDt.AddSeconds(1);
                    endDt = endDt.AddSeconds(1);
                }

                var checkSR = new ServiceRecordDC();

                if (checkSR == null)
                {
                    checkSR = new ServiceRecordDC();
                }

                checkSR.Goals = Model.SelectedGoals;

                checkSR.Start = startDt;
                checkSR.End = endDt;

                if (Model.Employee.EmployeeOid != null)
                {
                    checkSR.Employee = MobileSessionFacade.LoggedInCompactEmployee;


                    model.CostBearer2SupportConceptOid = costbearerOId;

                    var sc = Model.SupportConcepts.FirstOrDefault(fod => fod.CostBearerRelations.Any(a => a.CostBearer2SupportConceptOid.HasValue && a.CostBearer2SupportConceptOid.Value.Equals(Model.CostBearer2SupportConceptOid)));

                    if (sc != null)
                    {
                        if (sc.SupportConceptOid != null)
                        {
                            checkSR.SupportConcept = CustomerService.LoadCompactSupportConceptDC(sc.SupportConceptOid.Value, Model.Employee.EmployeeOid);
                        }

                        checkSR.Customer = sc.Customer;
                        var cb2ScRel = sc.CostBearerRelations.First(f => f.CostBearer2SupportConceptOid.HasValue && f.CostBearer2SupportConceptOid.Equals(Model.CostBearer2SupportConceptOid));
                        checkSR.CostBearer = cb2ScRel.CostBearer;
                        var intervall = checkSR.CostBearer.ActualMinuteIntervall;

                        if (intervall > 0)
                        {
                            checkSR.RoundedDuration = dauer % intervall != 0 ? dauer + (intervall - (dauer % intervall)) : dauer;
                        }

                        checkSR.CostBearer2SupportConceptOid = Model.CostBearer2SupportConceptOid;
                    }
                }

                checkSR.IP = Request.UserHostAddress;
                checkSR.InsertedOn = DateTime.Now;
                checkSR.InsUser = String.Format("{0} {1}", MobileSessionFacade.LoggedInEmployee.FirstName, MobileSessionFacade.LoggedInEmployee.LastName);

                if (leistung != null || leistung == "")
                    Model.SelectedServiceDescriptionOid = Convert.ToInt64(leistung);
                else
                    Model.SelectedServiceDescriptionOid = 6;

                checkSR.ServiceDescription = OperationsService.GetServiceDescription(Model.SelectedServiceDescriptionOid.Value);

                var man = OperationsService.GetMandator();
                var s = man.Settings ?? String.Empty;
                var einzeln = s.Split(';');
                var g = einzeln.ToList().FirstOrDefault(f => f.Contains("MaxDaysEditServiceRecordsAllowed"));
                var t = g != null ? int.Parse(g.Split('=')[1]) : 0;

                SupportConceptStatisticsDC stats = null;
                if (Model.CostBearer2SupportConceptOid != null && Model.CostBearer2SupportConceptOid > 0)
                {
                    stats = OperationsService.CreateSupportConceptStatistics(Model.CostBearer2SupportConceptOid.Value, DateTime.Now);
                }

                var result = OperationsService.ValidateServiceRecordEntry(checkSR, stats, t, false, new List<long> { checkSR.Employee.EmployeeOid });

                if (result.Count != 0)
                {
                    if (result[0].EndDate.Day <= date.Day && result[0].EndDate.Year <= date.Year && result[0].EndDate.Month <= date.Month ||
                        result[0].EndDate.Day >= date.Day && result[0].EndDate.Year <= date.Year && result[0].EndDate.Month <= date.Month ||
                        result[0].EndDate.Day <= date.Day && result[0].EndDate.Year <= date.Year && result[0].EndDate.Month >= date.Month ||
                        result[0].EndDate.Day >= date.Day && result[0].EndDate.Year <= date.Year && result[0].EndDate.Month >= date.Month)
                    {
                        Model.ErrorWert = 4;
                        return false;
                    }
                    else
                    {
                        Model.ErrorWert = 3;
                        return false;
                    }
                }
                else
                {
                    Model.ErrorWert = 1;
                    return true;
                }         
        }




        private static DateTime ConvertTimeStringToDateTime(String timeString)
        {
            var dt = DateTime.Now.Date;

            if (String.IsNullOrEmpty(timeString))
            {
                timeString = "0000";
            }

            var numberString = Regex.Replace(timeString, "[^0-9]", "");

            if (numberString.Length == 2)
            {
                numberString = numberString + "00";
            }

            while (numberString.Length < 4)
            {
                numberString = "0" + numberString;
            }
            if (numberString.Length > 4)
            {
                numberString = numberString.Substring(0, 4);
            }

            var hours = Convert.ToInt32(numberString.Substring(0, 2));
            var minutes = Convert.ToInt32(numberString.Substring(2, 2));

            dt = dt.AddHours(hours);
            dt = dt.AddMinutes(minutes);

            return dt;
        }

        struct ValidationStruct
        {
            public List<ServiceRecordValidationResultDC> ValidationResults { get; set; }
            public Dictionary<int, bool> Rights { get; set; }
            public String MaxDaysEditServiceRecordsAllowed { get; set; }
        }

        public void SetViewMode()
        {
            if (Model == null)
            {
                RedirectToActionPermanent("Index", "Login");
                return;
            }

            Model.SelectedCustomer = null;
            Model.SelectedCustomerOid = null;
        }

        public String GetSelectedSupportConceptCustomer()
        {
            return Model.SelectedSupportConcept == null ? "NoSupportConceptSelected" : SerializeObject(Model.SelectedSupportConcept.Customer.CustomerOid);
        }

        public String GetSelectedCustomer(long customerOid)
        {
            if (Model == null)
            {
                return "SessionTimeout";
            }

            Model.SelectedCustomer = Model.Customers.FirstOrDefault(f => f.CustomerOid.HasValue && f.CustomerOid.Value.Equals(customerOid));
            Model.SelectedCustomerOid = customerOid;
            var erg = SerializeObject(getJSONCustomer(Model.SelectedCustomer));
            return erg;
        }

        private static JSONCustomer getJSONCustomer(CustomerDC pCustomer)
        {
            return new JSONCustomer(pCustomer);
        }

        public void SetServiceRecordEmployee(long employeeOid)
        {
            if (Model == null)
            {
                RedirectToActionPermanent("Index", "Login");
                return;
            }

            Model.SelectedEmployee = MainModel.AllEmployees.First(f => f.EmployeeOid.Equals(employeeOid));
        }

        public string CheckToken(string token)
        {
            // Token wird gecheckt...

            if(token != null && token.Equals("abcd"))
            {
                return SerializeObject("localhost;demo");
            }

            return null;
        }
    }

    class JSONCustomer
    {
        public String Vorname { get; set; }
        public String Nachname { get; set; }
        public String Geburtstag { get; set; }
        public String Geschlecht { get; set; }

        public String Adresszusatz { get; set; }
        public String Strasse { get; set; }
        public String Postleitzahl { get; set; }
        public String Ort { get; set; }

        public String RechnungsadresseName { get; set; }
        public String RechnungsadresseStrasse { get; set; }
        public String RechnungsadressePostleitzahl { get; set; }
        public String RechnungsadresseOrt { get; set; }

        public String EMail { get; set; }
        public String Fax { get; set; }
        public String Telefon { get; set; }
        public String Handy { get; set; }

        public List<Umfeldsperson> Umfeldpersonen { get; set; }

        public JSONCustomer(CustomerDC init)
        {
            Vorname = init.FirstName;
            Nachname = init.LastName;
            Geburtstag = init.DateOfBirth == null ? String.Empty : init.DateOfBirth.Value.ToShortDateString();
            Geschlecht = init.Sex == Sex.Male ? "Männlich" : "Weiblich";

            Adresszusatz = init.AddressLine1;
            Strasse = init.Street;
            Postleitzahl = init.PostalCode;
            Ort = init.Town;

            RechnungsadresseName = init.InvoiceAddressLine1;
            RechnungsadresseStrasse = init.InvoiceAddressStreet;
            RechnungsadressePostleitzahl = init.InvoiceAddressPostalCode;
            RechnungsadresseOrt = init.InvoiceAddressTown;

           

            foreach (var iContactDC in init.ContactInformations)
            {
                if (iContactDC.ContactType == ContactType.business_Mail)
                {
                    EMail = iContactDC.ContactValue;
                }

                if (iContactDC.ContactType == ContactType.business_Fax)
                {
                    Fax = iContactDC.ContactValue;
                }

                if (iContactDC.ContactType == ContactType.business_Phone)
                {
                    Telefon = iContactDC.ContactValue;
                }

                if (iContactDC.ContactType == ContactType.business_MobilePhone)
                {
                    Handy = iContactDC.ContactValue;
                }
            }

            Umfeldpersonen = new List<Umfeldsperson>();
            foreach (var rel in init.EnvironmentPersons)
            {
                Umfeldpersonen.Add(new Umfeldsperson(rel));
            }
        }
    }

    class Umfeldsperson
    {
        public String Vorname { get; set; }
        public String Nachname { get; set; }
        public String StrNameNr { get; set; }
        public String PLZOrt { get; set; }
        public String TelNr { get; set; }
        public String Mobil { get; set; }
        public String EMail { get; set; }
        public String Fax { get; set; }
        public String Rolle { get; set; }
        public String Titel { get; set; }

        public Umfeldsperson(CustomerPersonRelationDC umfeldspersonDC)
        {
            var person = umfeldspersonDC.Person;

            Rolle = person.Function;
            Vorname = person.FirstName;
            Nachname = person.LastName;
            StrNameNr = person.Street;
            PLZOrt = String.Format("{0} {1}", person.PostalCode, person.Town);
            TelNr = person.Communication1;
            Mobil = person.Communication2;
            EMail = person.Communication3;
            Fax = person.Communication4;
            Titel = person.Title;
        }
    }
}
