using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using GreenTree.Nachtragsmanagement.Web.Framework;
using GreenTree.Nachtragsmanagement.Core.Domain;
using System.Reflection;
using GreenTree.Nachtragsmanagement.Core;
using Autofac;
using GreenTree.Nachtragsmanagement.Web.Framework.Mvc.Routes;
using GreenTree.Nachtragsmanagement.Web.App_Start;
using System.Web.Optimization;
using FluentValidation.Mvc;
using GreenTree.Nachtragsmanagement.Web.Validation;
using GreenTree.Nachtragsmanagement.Services.User;
using GreenTree.Nachtragsmanagement.Data;
using GreenTree.Nachtragsmanagement.Core.Domain.Misc;
using GreenTree.Nachtragsmanagement.Core.Domain.User;
using GreenTree.Nachtragsmanagement.Core.Domain.Deviation;
using GreenTree.Nachtragsmanagement.Services.Deviation;
using GreenTree.Nachtragsmanagement.Core.Domain.Site;
using GreenTree.Nachtragsmanagement.Core.Domain.Appendix;
using GreenTree.Nachtragsmanagement.Services.Appendix;
using GreenTree.Nachtragsmanagement.Services.Site;
using GreenTree.Nachtragsmanagement.Core.Plugins;
using GreenTree.Nachtragsmanagement.Services.Configuration;
using GreenTree.Nachtragsmanagement.Core.Domain.Config;
using GreenTree.Nachtragsmanagement.Services.Misc;
using GreenTree.Nachtragsmanagement.Services.Scheduling;
using GreenTree.Nachtragsmanagement.Services.Logging;
using GreenTree.Nachtragsmanagement.Web.Extensions;

namespace GreenTree.Nachtragsmanagement.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            try
            {
                AreaRegistration.RegisterAllAreas();

                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);

                BundleConfig.RegisterBundles(BundleTable.Bundles);

                ModelBinders.Binders.DefaultBinder = new DevExpress.Web.Mvc.DevExpressEditorsBinder();

                ApplicationContext.InitApplication();
                ApplicationContext.InitPluginRoutes(RouteTable.Routes);

                var logger = Singleton<IContainer>.Instance.Resolve<ILogger>();

                FunctionConfig.RegisterFunctions();

                FluentValidationModelValidatorProvider.Configure(provider =>
                {
                    provider.ValidatorFactory = new AppendixValidatorFactory();
                });

                var notificationScheduler = Singleton<IContainer>.Instance.Resolve<INotificationScheduler>();

                if (notificationScheduler != null)
                    notificationScheduler.Start();

                GridViewSettingsHelper._configurationService = Singleton<IContainer>.Instance.Resolve<IConfigurationService>();

                logger.Information("Anwendung erfolgreich gestartet.");
            }
            catch (Exception ex)
            {
                var logger = Singleton<IContainer>.Instance.Resolve<ILogger>();

                if (logger != null)
                    logger.Fatal("Fehler bei Start der Anwendung.", ex, null);
            }

            DevExpress.Web.ASPxWebControl.CallbackError += Application_Error;

            //GenerateTestData();
        }

        /// <summary>
        /// Event handler for general exceptions
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e) 
        {
            var logger = Singleton<IContainer>.Instance.Resolve<ILogger>();

            var exception = HttpContext.Current.Server.GetLastError();

            if (logger != null)
                logger.Error("Allgemeiner Fehler aufgetreten.", exception, null);
        }

        #region Test

        /// <summary>
        /// Generates test data for testing the application
        /// </summary>
        private void GenerateTestData()
        {
            // Get services

            var userService = Singleton<IContainer>.Instance.Resolve<IUserService>();
            var deviationService = Singleton<IContainer>.Instance.Resolve<IDeviationService>();
            var appendixService = Singleton<IContainer>.Instance.Resolve<IAppendixService>();
            var siteService = Singleton<IContainer>.Instance.Resolve<ISiteService>();
            var configurationService = Singleton<IContainer>.Instance.Resolve<IConfigurationService>();
            var miscService = Singleton<IContainer>.Instance.Resolve<IMiscService>();
            var dbContext = Singleton<IContainer>.Instance.Resolve<IDbContext>();

            try
            {
                // Check if test data is already created

                var isTestDataGeneratedEntity = dbContext.Get<DbContextSpec>().FirstOrDefault(d => d.Name == "IsTestDataGenerated");

                if (isTestDataGeneratedEntity != null && Convert.ToBoolean(isTestDataGeneratedEntity.Value))
                    return;

                // Create roles

                var r1 = new Role
                {
                    Description = "Administrator",
                    Level = 100,
                    SeeOnlyAssigned = false
                };
                userService.InsertRole(r1);

                var r2 = new Role
                {
                    Description = "Kaufmann",
                    Level = 10,
                    SeeOnlyAssigned = true
                };
                userService.InsertRole(r2);

                var r3 = new Role
                {
                    Description = "Nachtragsmanager",
                    Level = 10,
                    SeeOnlyAssigned = false
                };
                userService.InsertRole(r3);

                var r4 = new Role
                {
                    Description = "Bauleiter",
                    Level = 10,
                    SeeOnlyAssigned = true
                };
                userService.InsertRole(r4);

                // Create users

                var u1 = new User
                {
                    Forename = "Arne",
                    Lastname = "Diekmann",
                    CustomNumber = "a.diekmann",
                    MailAddress = "a.diekmann@greentreestudios.de",
                    Password = StaticHelper.GetMD5Hash("14595809")
                };
                userService.InsertUser(u1);

                var u2 = new User
                {
                    Forename = "Rocco",
                    Lastname = "Lavella",
                    CustomNumber = "r.lavella",
                    MailAddress = "lavella@schweerbau.de",
                    Password = StaticHelper.GetMD5Hash("lavella")
                };
                userService.InsertUser(u2);

                var u3 = new User
                {
                    Forename = "Felix",
                    Lastname = "Bramstedt",
                    CustomNumber = "f.bramstedt",
                    MailAddress = "bramstedt@schweerbau.de",
                    Password = StaticHelper.GetMD5Hash("bramstedt")
                };
                userService.InsertUser(u3);

                var u4 = new User
                {
                    Forename = "Kletus",
                    Lastname = "Lingemann",
                    CustomNumber = "k.lingemann",
                    MailAddress = "lingemann@schweerbau.de",
                    Password = StaticHelper.GetMD5Hash("lingemann")
                };
                userService.InsertUser(u4);

                var u5 = new User
                {
                    Forename = "Max",
                    Lastname = "Moede",
                    CustomNumber = "m.moede",
                    MailAddress = "moede@schweerbau.de",
                    Password = StaticHelper.GetMD5Hash("moede")
                };
                userService.InsertUser(u5);

                var u6 = new User
                {
                    Forename = "Max",
                    Lastname = "Dammeier",
                    CustomNumber = "m.dammeier",
                    MailAddress = "dammeier@schweerbau.de",
                    Password = StaticHelper.GetMD5Hash("dammeier")
                };
                userService.InsertUser(u6);

                var u7 = new User
                {
                    Forename = "Max",
                    Lastname = "Poppe",
                    CustomNumber = "m.poppe",
                    MailAddress = "poppe@schweerbau.de",
                    Password = StaticHelper.GetMD5Hash("poppe")
                };
                userService.InsertUser(u7);

                var u8 = new User
                {
                    Forename = "Max",
                    Lastname = "Lehmann",
                    CustomNumber = "m.lehmann",
                    MailAddress = "lehmann@schweerbau.de",
                    Password = StaticHelper.GetMD5Hash("poppe")
                };
                userService.InsertUser(u8);

                var u9 = new User
                {
                    Forename = "Max",
                    Lastname = "Wernecke",
                    CustomNumber = "m.wernecke",
                    MailAddress = "wernecke@schweerbau.de",
                    Password = StaticHelper.GetMD5Hash("wernecke")
                };
                userService.InsertUser(u9);

                // Add users to roles

                u1.Roles.Add(r1);
                u2.Roles.Add(r1);
                u3.Roles.Add(r1);
                u4.Roles.Add(r3);
                u8.Roles.Add(r3);
                u5.Roles.Add(r4);
                u7.Roles.Add(r4);
                u6.Roles.Add(r2);
                u9.Roles.Add(r2);

                // Get all functions and add them to the admin role

                var allFunctions = userService.GetAllFunctions();

                r1.SetFunctions(allFunctions);
                userService.UpdateRole(r1);

                // Get all appendix manager function and add them to the apendix manager / merchant role

                var deviationFunctions = allFunctions
                    .Where(f => f.Name.StartsWith("Deviation"));

                foreach (var function in deviationFunctions)
                {
                    r2.Functions.Add(function);
                    r3.Functions.Add(function);
                    r4.Functions.Add(function);
                }

                var appendixFunctions = allFunctions
                    .Where(f => f.Name.StartsWith("Appendix"));

                foreach (var function in appendixFunctions)
                {
                    r2.Functions.Add(function);
                    r3.Functions.Add(function);
                    r4.Functions.Add(function);
                }

                var siteFunctions = allFunctions
                    .Where(f => f.Name.StartsWith("Site") && f.Name != "Site-Sites-Delete");

                foreach (var function in siteFunctions)
                {
                    r2.Functions.Add(function);
                    r3.Functions.Add(function);
                    r4.Functions.Add(function);
                }

                userService.UpdateRole(r2);
                userService.UpdateRole(r3);
                userService.UpdateRole(r4);

                // Create appendix base data

                var categories = new[]
                {
                    new Category { Description = "RPM" },
                    new Category { Description = "RM" },
                    new Category { Description = "Stopftechnik" },
                    new Category { Description = "Umbauzug" },
                    new Category { Description = "Logistik" },
                    new Category { Description = "Oberbau" },
                    new Category { Description = "Erdbau" },
                    new Category { Description = "Kabeltiefbau" },
                    new Category { Description = "Entwässerung" },
                    new Category { Description = "Sonstiges" }
                };

                foreach (var category in categories)
                    appendixService.InsertCategory(category);

                var states = new[]
                {
                    new State { Description = "Offen", IsDefault = true, HexColor = "#FFFFFF" },
                    new State { Description = "Erinnerung Verhandlung", IsDefault = false, HexColor = "#FF817F" },
                    new State { Description = "Verhandelt", IsDefault = false, HexColor = "#E5E5E5" },
                    new State { Description = "Erledigt / Entfällt", IsDefault = false, HexColor = "#8ECC8E" }
                };

                foreach (var state in states)
                    appendixService.InsertState(state);

                var appendices = new[]
                {
                    new Appendix
                    {
                        CustomNumber = "3",
                        Description = "Lückenschluss Weiche 523",
                        State = states[0],
                        StateId = states[0].Id,
                        CategoryValues =
                        {
                            new CategoryValue { Category = categories[2], CategoryId = categories[2].Id, Value = 44000 },
                            new CategoryValue { Category = categories[3], CategoryId = categories[3].Id, Value = 30000 },
                        },
                        Value = Convert.ToDecimal(74833.6),
                        Percentage = (decimal)0.5,
                        NegotiationValue = 70000,
                        OfferingDate = new DateTime(2016, 12, 20),
                        Comment = "hier 3 % NA enthalten = Delta zu iTWO  = 77148,04€, Abgabeddatum per Mail, Post später"
                    },
                    new Appendix
                    {
                        CustomNumber = "6",
                        Description = "Erschwerniss masch. Gleisbau ZEB 22",
                        State = states[0],
                        StateId = states[0].Id,
                        CategoryValues =
                        {
                            new CategoryValue { Category = categories[0], CategoryId = categories[0].Id, Value = 43000 }
                        },
                        Value = Convert.ToDecimal(43514.35),
                        Percentage = (decimal)0.5,
                        NegotiationValue = 40000,
                        OfferingDate = new DateTime(2016, 12, 20),
                        Comment = "Teilweise Abrechnung über HLV in Höhe von 5322,12€ (nicht in Summe oben enthalten) hier 3 % NA enthalten = Delta zu iTWO  = 44860,15€ Abgabeddatum per Mail, Post später"
                    },
                    new Appendix
                    {
                        CustomNumber = "1",
                        Description = "Umsetzen von Haufwerken",
                        State = states[0],
                        StateId = states[0].Id,
                        CategoryValues =
                        {
                            new CategoryValue { Category = categories[9], CategoryId = categories[9].Id, Value = 2500 }
                        },
                        Value = Convert.ToDecimal(2549.18),
                        Percentage = (decimal)0.5,
                        NegotiationValue = 2000,
                        OfferingDate = new DateTime(2017, 2, 2),
                        Comment = "Beginn der Frist der Nachtragsprüfung 16.02.17"
                    },
                    new Appendix
                    {
                        CustomNumber = "2",
                        Description = "Nichtbereitstellung der Ladevorrichtung",
                        State = states[0],
                        StateId = states[0].Id,
                        CategoryValues =
                        {
                            new CategoryValue { Category = categories[4], CategoryId = categories[4].Id }
                        },
                        Value = Convert.ToDecimal(23738.06),
                        Percentage = (decimal)0.5,
                        NegotiationValue = 20000,
                        OfferingDate = new DateTime(2017, 2, 3),
                        Comment = "Aufmaße noch nicht erstellt"
                    }
                };

                foreach (var appendix in appendices)
                    appendixService.InsertAppendix(appendix);

                // Create site base data

                var sites = new[]
                {
                    new Site
                    {
                        CustomNumber = "2101000",
                        Description = "POS Nord Kaiserslautern Los 19-21",
                        Appendices =
                        {
                            appendices[0],
                            appendices[1]
                        },
                        Finished = false,
                        Start = new DateTime(2016, 1, 1),
                        Users =
                        {
                            u4,
                            u5,
                            u6
                        }
                    },
                    new Site
                    {
                        CustomNumber = "211200",
                        Description = "GE Geisenheim-Rüdesheim",
                        Appendices =
                        {
                            appendices[2],
                            appendices[3]
                        },
                        Finished = false,
                        Start = new DateTime(2016, 1, 1),
                        Users =
                        {
                            u7,
                            u8,
                            u9
                        }
                    }
                };

                foreach (var site in sites)
                    siteService.InsertSite(site);

                // Create deviation base data

                var kinds = new[]
                {
                    new Kind { Shortance = "MK", Description = "Mehrkosten", IsDefault = true },
                    new Kind { Shortance = "BH", Description = "Behinderung", IsDefault = false },
                    new Kind { Shortance = "BD", Description = "Bedenken", IsDefault = false }
                };

                foreach (var kind in kinds)
                    deviationService.InsertKind(kind);

                var disturbances = new[]
                {
                    new Disturbance { Description = "RPM" },
                    new Disturbance { Description = "RM" },
                    new Disturbance { Description = "Stopftechnik" },
                    new Disturbance { Description = "Umbauzug" },
                    new Disturbance { Description = "Logistik" },
                    new Disturbance { Description = "Oberbau" },
                    new Disturbance { Description = "Erdbau" },
                    new Disturbance { Description = "Kabeltiefbau" },
                    new Disturbance { Description = "Entwässerung" },
                    new Disturbance { Description = "Sonstiges" }
                };

                foreach (var disturbance in disturbances)
                    deviationService.InsertDisturbance(disturbance);

                var statuses = new[]
                {
                    new Status { Description = "Standard", IsDefault = true },
                    new Status { Description = "Entfällt", IsDefault = false },
                    new Status { Description = "Strittig", IsDefault = false },
                    new Status { Description = "Abr. über HLV", IsDefault = false }
                };

                foreach (var status in statuses)
                    deviationService.InsertStatus(status);

                var deviations = new[]
                {
                    new Deviation
                    {
                        CustomNumber = "1",
                        Description = "Mehrleistung Stopfen",
                        Kind = kinds[0],
                        KindId = kinds[0].Id,
                        DisturbanceValues =
                        {
                            new DisturbanceValue { Disturbance = disturbances[2], DisturbanceId = disturbances[2].Id, Value = 40000 }
                        },
                        Status = statuses[0],
                        StatusId = statuses[0].Id,
                        Value = 40000,
                        Percentage = 1,
                        ReceiptDate = new DateTime(2016, 8, 1),
                        Appendix = appendices[0],
                        AppendixId = appendices[0].Id,
                        AppendixDate = appendices[0].OfferingDate
                    },
                    new Deviation
                    {
                        CustomNumber = "2",
                        Description = "Bodenausbau konventionell",
                        Kind = kinds[0],
                        KindId = kinds[0].Id,
                        DisturbanceValues =
                        {
                            new DisturbanceValue { Disturbance = disturbances[6], DisturbanceId = disturbances[6].Id, Value = 30000 }
                        },
                        Status = statuses[1],
                        StatusId = statuses[1].Id,
                        Value = 30000,
                        Percentage = 0,
                        ReceiptDate = new DateTime(2016, 8, 10),
                        Appendix = appendices[0],
                        AppendixId = appendices[0].Id,
                        AppendixDate = appendices[0].OfferingDate
                    },
                    new Deviation
                    {
                        CustomNumber = "3",
                        Description = "Einbau PSS im Weichenbereich",
                        Kind = kinds[0],
                        KindId = kinds[0].Id,
                        DisturbanceValues =
                        {
                            new DisturbanceValue { Disturbance = disturbances[6], DisturbanceId = disturbances[6].Id, Value = 2000 }
                        },
                        Status = statuses[0],
                        StatusId = statuses[0].Id,
                        Value = 2000,
                        Percentage = 1,
                        ReceiptDate = new DateTime(2016, 8, 15),
                        Appendix = appendices[1],
                        AppendixId = appendices[1].Id,
                        AppendixDate = appendices[1].OfferingDate
                    },
                    new Deviation
                    {
                        CustomNumber = "4",
                        Description = "Hindernisse bei der PLV mit RPM",
                        Kind = kinds[1],
                        KindId = kinds[1].Id,
                        DisturbanceValues =
                        {
                            new DisturbanceValue { Disturbance = disturbances[0], DisturbanceId = disturbances[0].Id, Value = 40000 }
                        },
                        Status = statuses[2],
                        StatusId = statuses[2].Id,
                        Value = 40000,
                        Percentage = (decimal)0.3,
                        ReceiptDate = new DateTime(2016, 8, 20),
                        Site = sites[0],
                        SiteId = sites[0].Id
                    },
                    new Deviation
                    {
                        CustomNumber = "1",
                        Description = "Umsetzen von Haufwerken",
                        Kind = kinds[0],
                        KindId = kinds[0].Id,
                        DisturbanceValues =
                        {
                            new DisturbanceValue { Disturbance = disturbances[6], DisturbanceId = disturbances[6].Id, Value = 2500 }
                        },
                        Status = statuses[0],
                        StatusId = statuses[0].Id,
                        Value = 2500,
                        Percentage = 1,
                        ReceiptDate = new DateTime(2017, 1, 5),
                        Appendix = appendices[2],
                        AppendixId = appendices[2].Id,
                        AppendixDate = appendices[2].OfferingDate
                    },
                    new Deviation
                    {
                        CustomNumber = "2",
                        Description = "Nichtbereitsstellung der Ladevorrichtung Nr. 1",
                        Kind = kinds[0],
                        KindId = kinds[0].Id,
                        DisturbanceValues =
                        {
                            new DisturbanceValue { Disturbance = disturbances[5], DisturbanceId = disturbances[5].Id, Value = 10000 }
                        },
                        Status = statuses[0],
                        StatusId = statuses[0].Id,
                        Value = 10000,
                        Percentage = 1,
                        ReceiptDate = new DateTime(2017, 1, 7),
                        Appendix = appendices[3],
                        AppendixId = appendices[3].Id,
                        AppendixDate = appendices[3].OfferingDate
                    },
                    new Deviation
                    {
                        CustomNumber = "5",
                        Description = "Nichtbereitsstellung der Ladevorrichtung Nr. 2",
                        Kind = kinds[0],
                        KindId = kinds[0].Id,
                        DisturbanceValues =
                        {
                            new DisturbanceValue { Disturbance = disturbances[5], DisturbanceId = disturbances[5].Id, Value = 10000 }
                        },
                        Status = statuses[3],
                        StatusId = statuses[3].Id,
                        Value = 10000,
                        Percentage = 1,
                        ReceiptDate = new DateTime(2017, 1, 10),
                        Appendix = appendices[3],
                        AppendixId = appendices[3].Id,
                        AppendixDate = appendices[3].OfferingDate
                    },
                    new Deviation
                    {
                        CustomNumber = "6",
                        Description = "Verspannung Los 2",
                        Kind = kinds[0],
                        KindId = kinds[0].Id,
                        DisturbanceValues =
                        {
                            new DisturbanceValue { Disturbance = disturbances[5], DisturbanceId = disturbances[5].Id, Value = 6000 }
                        },
                        Status = statuses[2],
                        StatusId = statuses[2].Id,
                        Value = 6000,
                        Percentage = (decimal)0.5,
                        ReceiptDate = new DateTime(2017, 1, 12),
                        Site = sites[1],
                        SiteId = sites[1].Id
                    }
                };

                foreach (var deviation in deviations)
                    deviationService.InsertDeviation(deviation);

                // Create config base data

                var configItems = new[]
                {
                    new ConfigItem
                    {
                        Name = "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationDate.AgeDays",
                        TypeFullName = "System.Int32",
                        Value = "56",
                        Description =
                            "Die Anzahl der Tage ab dem Angebotstermin eines Nachtrags, damit er bei der Überprüfung des " +
                            "Verhandlungsdatums mit berücksichtigt werden soll"
                    },
                    new ConfigItem
                    {
                        Name = "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationDate.StateSet",
                        TypeFullName = "System.Int32",
                        Value = states[1].Id.ToString(),
                        Description =
                            "Die ID des Nachtragsstatus, auf den der Nachtrag gesetzt wird, nachdem er bei der Überprüfung des " +
                            "Verhandlungsdatums geprüft wurde"
                    },
                    new ConfigItem
                    {
                        Name = "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationDate.Interval",
                        TypeFullName = "System.Int32",
                        Value = "2",
                        Description =
                            "Der Wocheninterval, in dem weitere Benachrichtigungen über nicht verhandelte Nachträge gesendet werden " +
                            "soll"
                    },
                    new ConfigItem
                    {
                        Name = "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationProtocol.AgeDays",
                        TypeFullName = "System.Int32",
                        Value = "14",
                        Description =
                            "Die Anzahl der Tage ab dem Verhandlungstermin eines Nachtrags, damit er bei der Überprüfung des " +
                            "Protokolls mit berücksichtigt werden soll"
                    },
                    new ConfigItem
                    {
                        Name = "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationProtocol.StateCondition",
                        TypeFullName = "System.Int32",
                        Value = states[2].Id.ToString(),
                        Description =
                            "Die ID des Nachtragsstatus, den ein Nachtrag haben muss, damit er bei der Überprüfung des " +
                            "Verhandlungsprotokolls mit berücksichtigt werden soll"
                    },
                    new ConfigItem
                    {
                        Name = "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationProtocol.Interval",
                        TypeFullName = "System.Int32",
                        Value = "2",
                        Description =
                            "Der Wocheninterval, in dem weitere Benachrichtigungen über die Nachträge ohne Protokoll gesendet werden " +
                            "soll"
                    },
                    new ConfigItem
                    {
                        Name = "GreenTree.Nachtragsmanagement.DeviationNotificationPlugin.ProcessDeviationReceipt.AgeDaysLevel1",
                        TypeFullName = "System.Int32",
                        Value = "40",
                        Description =
                            "Die Anzahl der Tage ab dem Einreichungsdatum einer Vertragsabweichung, die bei der Überprüfung der " +
                            "Zuordnung eines Nachtrags, erreicht sein muss (Stufe 1)"
                    },
                    new ConfigItem
                    {
                        Name = "GreenTree.Nachtragsmanagement.DeviationNotificationPlugin.ProcessDeviationReceipt.AgeDaysLevel2",
                        TypeFullName = "System.Int32",
                        Value = "60",
                        Description =
                            "Die Anzahl der Tage ab dem Einreichungsdatum einer Vertragsabweichung, die bei der Überprüfung der " +
                            "Zuordnung eines Nachtrags, erreicht sein muss (Stufe 2)"
                    },
                };

                foreach (var configItem in configItems)
                    configurationService.InsertConfigItem(configItem);

                // Create notification base data

                var notifications = new[]
                {
                    new MailNotification
                    {
                        CronExpression = "0 0 6 ? * MON *",
                        NotificationPluginSystemName = "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin",
                        NotificationJobSystemName = "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationDate",
                        Users =
                        {
                            u1
                        }
                    }
                };

                foreach (var notification in notifications)
                    miscService.InsertMailNotification(notification);
            }
            finally
            {
                // Create DbContecSpecification object

                var db1 = new DbContextSpec
                {
                    Name = "IsTestDataGenerated",
                    Value = "True"
                };
                dbContext.Get<DbContextSpec>().Add(db1);

                dbContext.SaveChanges();
            }
        }

        #endregion
    }
}