/// <summary>
        /// Gets all notifications stored in a collection as an 'object'.
        /// These notifications must NOT be mistaken as the Model class Notification.
        /// The objects can be of either Job or Project
        /// 
        /// Examples on how to use this list:
        /// List<object> notifications = GetNotificationList();
        /// for (n in notifications) {
        ///     if (n is Job) {
        ///         // DO spesific Job code 
        ///         Job job = (Job)n;    
        ///         string date = job.expiryDate; // Will work
        ///     }
        ///     else if (n is Project) {
        ///         // Do spesific Project  code.
        ///         Project p = (Project)n;
        ///     }  
        /// }
        /// </summary>
        /// <returns>A list of objects suitable for to be dislayed to the user as notifications</returns>
        public List<Advert> GetNotificationList()
        {
            DbJob dbJob = new DbJob();
            DbNotification db = new DbNotification();
            JobsController jc = new JobsController();
            DbProject dbProject = new DbProject();
            IEnumerable<Notification> notifications = db.GetNotifications();

            List<Advert> notificationList = new List<Advert>();

            foreach (var n in notifications)
            {
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.id = " + n.id);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.jobUuid = " + n.jobUuid);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.projectUuid = " + n.projectUuid);

                if (!string.IsNullOrWhiteSpace(n.jobUuid))
                {

                    Job job = dbJob.GetJobByUuid(n.jobUuid);
                    job.companies = dbJob.GetAllCompaniesRelatedToJob(job);
                    notificationList.Add(job);
                }
                else
                {
                    Project project = dbProject.GetProjectByUuid(n.projectUuid);
                    project.companies = dbProject.GetAllCompaniesRelatedToProject(project);
                    notificationList.Add(project);
                }
            }
            return notificationList.OrderByDescending(a => a.published).ToList();
        }
        /// <summary>
        /// Deserializes a singular Project with children objects. 
        /// </summary>
        /// <param name="jsonString">Serialized data contain information about project and its children</param>
        /// <returns>A deserialized Project object</returns>
        private Project Deserialize(string jsonString)
        {
            DbProject db = new DbProject();
            Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
            System.Diagnostics.Debug.WriteLine("DeserializeApiData. Printing Key Value:");
            string[] keys = dict.Keys.ToArray();
            Project p = new Project();
            p.companies = new List<Company>();
            p.courses = new List<Course>();
            p.studyGroups = new List<StudyGroup>();
            p.jobTypes = new List<JobType>();

            foreach (var key in keys)
            {
                System.Diagnostics.Debug.WriteLine("key: " + key);
                System.Diagnostics.Debug.WriteLine("value: " + dict[key].ToString());
                /*
                if (!key.Equals("companies") || !key.Equals("courses") || !key.Equals("degrees")
                    || !key.Equals("jobTypes") || !key.Equals("studyGroup")) {} */
                if (key.Equals("uuid"))
                {
                    p.uuid = dict[key].ToString();
                }
                if (key.Equals("title"))
                {
                    p.title = dict[key].ToString();
                }

                /*
                if (key.Equals("description"))
                {
                    p.description = dict[key].ToString();
                }
                */

                if (key.Equals("webpage"))
                {
                    p.webpage = dict[key].ToString();
                }
                if (key.Equals("published"))
                {
                    DateTime dateTime = (DateTime)dict[key];
                    p.published = long.Parse(dateTime.ToString("yyyyMMddHHmmss"));
                }

                if (key.Equals("modified"))
                {
                    DateTime dateTime = (DateTime)dict[key];
                    p.modified = long.Parse(dateTime.ToString("yyyyMMddHHmmss"));
                }

                if (key.Equals("companies"))
                {
                    // if not true then company already exist and needs to be updated.
                    CompaniesController cc = new CompaniesController();
                    DbCompany dbCompany = new DbCompany();
                    IEnumerable companies = (IEnumerable)dict[key];
                    //`Newtonsoft.Json.Linq.JArray'
                    System.Diagnostics.Debug.WriteLine("companies created");
                    foreach (var comp in companies)
                    {
                        System.Diagnostics.Debug.WriteLine("foreach initiated");
                        Dictionary<string, object> companyDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(comp.ToString());
                        Company company = cc.DeserializeCompany(companyDict);
                        System.Diagnostics.Debug.WriteLine("Deserialize: company.id: " + company.id);
                        p.companies.Add(company);
                        dbCompany.UpdateCompany(company);
                        System.Diagnostics.Debug.WriteLine("Deserialize: After j.companies.Add(company)");
                        string projectUuid = dict["uuid"].ToString();
                        dbCompany.InsertCompanyProject(company.id, projectUuid);

                    }
                }
     
                if (key.Equals("courses"))
                {
                    DbCourse dbCourse = new DbCourse();
                    IEnumerable courses = (IEnumerable)dict[key];
                    //Newtonsoft.Json.Linq.JArray'
                    System.Diagnostics.Debug.WriteLine("location created");
                    foreach (var course in courses)
                    {
                        System.Diagnostics.Debug.WriteLine("foreach initiated");
                        Dictionary<string, object> courseDict =
                            JsonConvert.DeserializeObject<Dictionary<string, object>>(course.ToString());

                        Course co = new Course();
                        if (courseDict.ContainsKey("id"))
                        {

                            co.id = courseDict["id"].ToString();
                            System.Diagnostics.Debug.WriteLine("Course id: " + co.id);
                        }

                        if (courseDict.ContainsKey("name"))
                        {
                            co.name = courseDict["name"].ToString();
                        }

                        dbCourse.InsertCourse(co);
                        p.courses.Add(co);
                        string projectUuid = dict["uuid"].ToString();
                        dbCourse.InsertCourseProject(co.id, projectUuid);
                    }
                }
                
               if (key.Equals("studyGroups"))
                {
                    DbStudyGroup dbStudyGroup = new DbStudyGroup();
                    IEnumerable studyGroups = (IEnumerable)dict[key];
                    //Newtonsoft.Json.Linq.JArray'
                    System.Diagnostics.Debug.WriteLine("studyGroups created");
                    foreach (var studyGroup in studyGroups)
                    {
                        System.Diagnostics.Debug.WriteLine("foreach initiated");
                        Dictionary<string, object> studyGroupDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(studyGroup.ToString());

                        
                        StudyGroup sg = new StudyGroup();
                        if (studyGroupDict.ContainsKey("id"))
                        {
                            sg.id = studyGroupDict["id"].ToString();
                        }

                        if (studyGroupDict.ContainsKey("name"))
                        {
                            sg.name = studyGroupDict["name"].ToString();
                        }

                        p.studyGroups.Add(sg);

                        string projectUuid = dict["uuid"].ToString();
                        dbStudyGroup.InsertStudyGroupProject(sg.id, projectUuid);

                    }
                }
                /*
                if (key.Equals("approvedCourses"))
                {
                    
                    Same as companies implementation
                    
                }

                if (key.Equals("degrees"))
                {
                    
                    Same as companies implementation
                    
                }
                */
                if (key.Equals("jobTypes"))
                {
                    DbJobType dbJobType = new DbJobType();
                    IEnumerable jobTypes = (IEnumerable)dict[key];
                    //Newtonsoft.Json.Linq.JArray'
                    System.Diagnostics.Debug.WriteLine("jobTypes created");
                    foreach (var jobType in jobTypes)
                    {
                        System.Diagnostics.Debug.WriteLine("foreach initiated");
                        Dictionary<string, object> jtDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jobType.ToString());

                        JobType jt = new JobType();
                        if (jtDict.ContainsKey("id"))
                        {
                            jt.id = jtDict["id"].ToString();
                        }

                        if (jtDict.ContainsKey("name"))
                        {
                            jt.name = jtDict["name"].ToString();
                        }

                        dbJobType.InsertJobType(jt);
                        System.Diagnostics.Debug.WriteLine("before p.jobTypes.Add(jt);");
                        p.jobTypes.Add(jt);

                        string projectUuid = dict["uuid"].ToString();
                        dbJobType.InsertJobTypeProject(jt.id, projectUuid);
                    }
                }
            }
            db.UpdateProject(p);
            return p;
        }
        /// <summary>
        /// Can return 3 different values:
        /// 1. "exists": No new project on the server. 
        /// 2. "incorrectCache": If the cache indicates that local database got data that the server doesnt have. 
        /// 3. "newData": There are new projects available on the server.
        /// 4. null: Check if Authenticater.Authorized has been set to false, if not the app could most likely not reach the server.
        /// </summary>
        /// <returns></returns>
        private async Task<String> CheckServerForNewData(List<string> studyGroups = null, Dictionary<string, string> filter = null)
        {
            string queryParams = CreateQueryParams(studyGroups, null, filter);
            //"api/v1/jobs/lastmodifed"
            string adress = Adress + "/" + "lastmodified" + queryParams;
            System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData - adress: " + adress);
            Uri url = new Uri(adress);
            System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData - url.ToString: " + url.ToString());

            var client = new HttpClient();
            DbStudent dbStudent = new DbStudent();
            string accessToken = dbStudent.GetStudentAccessToken();
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                Authenticater.Authorized = false;
                return null;
            }
            System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData - bearer: " + accessToken);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
            string jsonString = null;
            try
            {
                var response = await client.GetAsync(url);
                System.Diagnostics.Debug.WriteLine("CheckServerForNewData response " + response.StatusCode.ToString());
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData failed due to lack of Authorization");
                    Authenticater.Authorized = false;
                }

                else if (response.StatusCode == HttpStatusCode.OK)
                {
                    //results = await response.Content.ReadAsAsync<IEnumerable<Job>>();
                    jsonString = await response.Content.ReadAsStringAsync();
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: await client.GetAsync(\"url\") Failed");
                System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: Exception msg: " + e.Message);
                System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: Stack Trace: \n" + e.StackTrace);
                System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: End Of Stack Trace");
                return null;
            }
            if (jsonString != null)
            {
                // using <string, object> instead of <string, string> makes the date be stored in the right format when using .ToString()
                Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);

                if (dict.ContainsKey("uuid") && dict.ContainsKey("modified") && dict.ContainsKey("hash") && dict.ContainsKey("amountOfProjects"))
                {
                    string uuid = dict["uuid"].ToString();
                    DateTime dateTime = (DateTime)dict["modified"];
                    long modified = long.Parse(dateTime.ToString("yyyyMMddHHmmss"));
                    string uuids = dict["hash"].ToString();
                    int amountOfProjects = 0;
                    try
                    {
                        amountOfProjects = Int32.Parse(dict["amountOfProjects"].ToString());
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: await client.GetAsync(\"url\") Failed");
                        System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: Exception msg: " + ex.Message);
                        System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: Stack Trace: \n" + ex.StackTrace);
                        System.Diagnostics.Debug.WriteLine("ProjectController - CheckServerForNewData: End Of Stack Trace");
                        return null;
                    }

                    DbProject dbProject = new DbProject();
                    bool existInDb = dbProject.ExistsInDb(uuid, modified);
                    if (!existInDb)
                    {
                        return "newData";
                        //return existInDb;
                    }
                    var localProjects = dbProject.GetProjectsFromDbBasedOnFilter(studyGroups, filter, true);
                    int localDbCount = localProjects.Count();

                    StringBuilder sb = new StringBuilder();
                    foreach (var project in localProjects)
                    {
                        sb.Append(project.uuid);
                    }
                    string localUuids = Hasher.CalculateMd5Hash(sb.ToString());

                    // if there is a greater amount of jobs on that search filter then the job that exist 
                    // in the database has been inserted throught another search filter
                    if (uuids != localUuids)
                    {
                        if (amountOfProjects > localDbCount)
                        {
                            return "newData";
                            //return !existInDb;
                        }

                        return "incorrectCache";
                    }
                    return "exists";
                    //return existInDb;
                }
            }
            return null;
        }
        /// <summary>
        /// Gets a project based on optional filters.
        /// </summary>
        /// <param name="studyGroups">studyGroups can be a list of numerous studygroups ex: helse, idrettsfag, datateknologi </param>>
        /// <param name="filter">A dictionary where key can be: titles (values:title of the project), types (values: virksomhet, faglærer, etc...),
        ///                      courses (values: "IS-304" "DAT-304" osv). 
        ///                      Supports only 1 key at this current implementation!</param>
        /// <returns></returns>
        public async Task<IEnumerable<Project>> GetProjectsBasedOnFilter(List<string> studyGroups = null,
            Dictionary<string, string> filter = null)
        {
            DbProject db = new DbProject();
            //string adress = "http://kompetansetorgetserver1.azurewebsites.net/api/v1/projects";

            string instructions = await CheckServerForNewData(studyGroups, filter);
            if (!Authenticater.Authorized)
            {
                return null;
            }
            if (instructions != null)
            {
                System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter - instructions" + instructions);
                if (instructions == "exists")
                {
                    IEnumerable<Project> filteredProjects = db.GetProjectsFromDbBasedOnFilter(studyGroups, filter);
                    filteredProjects = db.GetAllCompaniesRelatedToProjects(filteredProjects.ToList());
                    return filteredProjects;
                }
            }

            DbStudent dbStudent = new DbStudent();

            string accessToken = dbStudent.GetStudentAccessToken();

            if (string.IsNullOrWhiteSpace(accessToken))
            {
                Authenticater.Authorized = false;
                return null;
            }
            string sortBy = "publish";
            string queryParams = CreateQueryParams(studyGroups, sortBy, filter);
            Uri url = new Uri(Adress + queryParams);
            System.Diagnostics.Debug.WriteLine("GetProjectsBasedOnFilter - url: " + url.ToString());

            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

            string jsonString = null;
            IEnumerable<Project> projects = null;
            try
            {
                var response = await client.GetAsync(url).ConfigureAwait(false);
                System.Diagnostics.Debug.WriteLine("GetProjectsBasedOnFilter response " + response.StatusCode.ToString());

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    System.Diagnostics.Debug.WriteLine("StudentsController - UpdateStudyGroupStudent failed due to lack of Authorization");
                    Authenticater.Authorized = false;
                }

                else if (response.StatusCode == HttpStatusCode.OK)
                {
                    jsonString = await response.Content.ReadAsStringAsync();
                    if (instructions != null && instructions == "incorrectCache")
                    {
                        var cachedProjects = db.GetProjectsFromDbBasedOnFilter(studyGroups, filter);
                        projects = DeserializeMany(jsonString);
                        // Get all jobs from that local dataset that was not in the dataset provided by the server
                        // These are manually deleted projects and have to be cleared from cache.
                        // linear search is ok because of small data set
                        var manuallyDeletedProjects = cachedProjects.Where(p => !projects.Any(cp2 => cp2.uuid == p.uuid));
                        db.DeleteObsoleteProjects(manuallyDeletedProjects.ToList());
                    }
                    else
                    {
                        projects = DeserializeMany(jsonString);
                    }
                }

                else
                {
                    System.Diagnostics.Debug.WriteLine("GetProjectsBasedOnFilter - Using the local database");
                    projects = db.GetProjectsFromDbBasedOnFilter(studyGroups, filter);
                    projects = db.GetAllCompaniesRelatedToProjects(projects.ToList());
                }
                return projects;
            }
            catch (Exception e)
            {
                // Hack workaround if mobil data and wifi is turned off
                try
                {
                    System.Diagnostics.Debug.WriteLine("GetProjectsBasedOnFilter - Using the local database");
                    projects = db.GetProjectsFromDbBasedOnFilter(studyGroups, filter);
                    projects = db.GetAllCompaniesRelatedToProjects(projects.ToList());
                    return projects;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("ProjectsController - GetProjectsBasedOnFilter: await client.GetAsync(\"url\") Failed");
                    System.Diagnostics.Debug.WriteLine("ProjectsController - GetProjectsBasedOnFilter: Exception msg: " + e.Message);
                    System.Diagnostics.Debug.WriteLine("ProjectsController - GetProjectsBasedOnFilter: Stack Trace: \n" + e.StackTrace);
                    System.Diagnostics.Debug.WriteLine("ProjectsController - GetProjectsBasedOnFilter: End Of Stack Trace");
                    return null;
                }
            }
        }
        /// <summary>
        /// Peter ikke se på denne metoden, den er kun for å teste databasen :D
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void TestProjectsFilterDb_OnClicked(object sender, EventArgs e)
        {
            List<string> studyGroups = new List<string>();
            string helse = Hasher.Base64Encode("helse");
            string datateknologi = Hasher.Base64Encode("datateknologi");
            studyGroups.Add(helse);
            studyGroups.Add(datateknologi);
            //LEGG FAGOMRÅDER TIL AKTIVT FILTER HER MED EN SWITCH ELLER LIGNENDE


            Dictionary<string, string> filter = new Dictionary<string, string>();
            string DAT304 = Hasher.Base64Encode("DAT-304");
            string virksomhet = Hasher.Base64Encode("virksomhet");
            filter.Add("courses", DAT304);
            filter.Add("types", virksomhet);

            DbProject pc = new DbProject();
            var projects = pc.GetProjectsFromDbBasedOnFilter(null, filter);

            if (projects == null)
            {
                System.Diagnostics.Debug.WriteLine("TestProjectsFilterDb:  was null aka failed!");
            }

            else
            {
                System.Diagnostics.Debug.WriteLine("TestProjectsFilterDb: projects.Count(): " +
                                                   projects.Count());

                foreach (var project in projects)
                {
                    System.Diagnostics.Debug.WriteLine("projects title: " + project.title);
                    if (project.companies != null)
                    {
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].id);

                    }
                }
            }

            var projects2 = pc.GetProjectsFromDbBasedOnFilter(studyGroups);

            if (projects2 == null)
            {
                System.Diagnostics.Debug.WriteLine("TestProjectsFilterDb:  was null aka failed!");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("GetProjectsFromDbBasedOnFilter: projects2.Count(): " +
                                                   projects2.Count());

                foreach (var project in projects2)
                {
                    System.Diagnostics.Debug.WriteLine("project2 title: " + project.title);
                    if (project.companies != null)
                    {
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].id);
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].name);
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].logo);

                    }
                }
            }

            var projects3 = pc.GetProjectsFromDbBasedOnFilter(studyGroups, filter);

            if (projects3 == null)
            {
                System.Diagnostics.Debug.WriteLine("TestProjectsFilterDb:  was null aka failed!");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("GetProjectsFromDbBasedOnFilter: projects3.Count(): " +
                                                   projects3.Count());

                foreach (var project in projects3)
                {
                    System.Diagnostics.Debug.WriteLine("projects3 title: " + project.title);
                    if (project.companies != null)
                    {
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].id);

                    }
                }
            }

            Dictionary<string, string> filter2 = new Dictionary<string, string>();
            //string titles = Hasher.Base64Encode("Strømavleser vha gammel mobil");
            filter2.Add("titles", "Strømavleser vha gammel mobil");
            Dictionary<string, string> filter3 = new Dictionary<string, string>();
            filter3.Add("titles", "vha");

            var projects4 = pc.GetProjectsFromDbBasedOnFilter(studyGroups, filter2);
            var projects5 = pc.GetProjectsFromDbBasedOnFilter(null, filter3);
            if (projects4 == null || projects5 == null)
            {
                System.Diagnostics.Debug.WriteLine("TestProjectsFilterDb:  was null aka failed!");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("GetProjectsFromDbBasedOnFilter: projects4.Count(): " +
                                                   projects4.Count());

                System.Diagnostics.Debug.WriteLine("GetProjectsFromDbBasedOnFilter: projects5.Count(): " +
                                                   projects5.Count());
                foreach (var project in projects4)
                {
                    System.Diagnostics.Debug.WriteLine("projects4 title: " + project.title);
                    if (project.companies != null)
                    {
                        System.Diagnostics.Debug.WriteLine("Companies is not null: " + project.companies[0].id);

                    }
                }
            }
        }
        /// <summary>
        /// Inserts a notification into the database.
        /// </summary>
        /// <param name="type">This param can either be job or project, and will determine what kind of notification it is.</param>
        /// <param name="typeUuid">the foreign key of type</param>
        public async Task InsertNotification(string type, string typeUuid)
        {
            System.Diagnostics.Debug.WriteLine("DbNotification - InsertNotification: initiated");

            Notification notification = new Notification();

            System.Diagnostics.Debug.WriteLine("DbNotification - InsertNotification: type: " + type);
            System.Diagnostics.Debug.WriteLine("DbNotification - InsertNotification: typeUuid: " + typeUuid);

            if (String.IsNullOrEmpty(typeUuid) || String.IsNullOrEmpty(type))
            {
                return;
            }

            if (type.Equals("job"))
            {
                // FIRST !!
                // insert a new job object matching the uuid as long as it doesn't exist
                System.Diagnostics.Debug.WriteLine("DbNotification - InsertNotification: new JobsController();");
                DbJob          dbJob = new DbJob();
                JobsController jc    = new JobsController();

                System.Diagnostics.Debug.WriteLine(
                    "DbNotification - InsertNotification: JobsController Created");

                dbJob.InsertJob(typeUuid);

                // SECOND insert the notification.
                notification.jobUuid = typeUuid;
                lock (DbContext.locker)
                {
                    Db.Insert(notification);
                }
                //THIRD: async get extra minimum info for the notification list.
                jc.UpdateJobFromServer(typeUuid);
            }

            else if (type.Equals("project"))
            {
                // FIRST !!
                // insert a new project object matching the uuid as long as it doesn't exist
                System.Diagnostics.Debug.WriteLine(
                    "DbNotification - InsertNotification: new ProjectsController();");
                ProjectsController pc        = new ProjectsController();
                DbProject          dbProject = new DbProject();
                System.Diagnostics.Debug.WriteLine(
                    "DbNotification - InsertNotification: ProjectsController Created");

                dbProject.InsertProject(typeUuid);

                // SECOND insert the notification.
                notification.projectUuid = typeUuid;
                lock (DbContext.locker)
                {
                    Db.Insert(notification);
                }
                //THIRD: async get extra minimum info for the notification list.
                pc.UpdateProjectFromServer(typeUuid);
            }
            System.Diagnostics.Debug.WriteLine("DbNotification - InsertNotification: Test: End of method");
        }
        /// <summary>
        /// Inserts a notification into the database.
        /// </summary>
        /// <param name="type">This param can either be job or project, and will determine what kind of notification it is.</param>
        /// <param name="typeUuid">the foreign key of type</param>
        public async Task InsertNotification(string type, string typeUuid)
        {
            System.Diagnostics.Debug.WriteLine("DbNotification - InsertNotification: initiated");

            Notification notification = new Notification();
            System.Diagnostics.Debug.WriteLine("DbNotification - InsertNotification: type: " + type);
            System.Diagnostics.Debug.WriteLine("DbNotification - InsertNotification: typeUuid: " + typeUuid);

            if (String.IsNullOrEmpty(typeUuid) || String.IsNullOrEmpty(type))
            {
                return;
            }

            if (type.Equals("job"))
            {
                // FIRST !!
                // insert a new job object matching the uuid as long as it doesn't exist
                System.Diagnostics.Debug.WriteLine("DbNotification - InsertNotification: new JobsController();");
                DbJob dbJob = new DbJob();
                JobsController jc = new JobsController();

                System.Diagnostics.Debug.WriteLine(
                    "DbNotification - InsertNotification: JobsController Created");

                dbJob.InsertJob(typeUuid);

                // SECOND insert the notification.
                notification.jobUuid = typeUuid;
                lock (DbContext.locker)
                {
                    Db.Insert(notification);
                }
                //THIRD: async get extra minimum info for the notification list.
                jc.UpdateJobFromServer(typeUuid);

            }

            else if (type.Equals("project"))
            {
                // FIRST !!
                // insert a new project object matching the uuid as long as it doesn't exist
                System.Diagnostics.Debug.WriteLine(
                    "DbNotification - InsertNotification: new ProjectsController();");
                ProjectsController pc = new ProjectsController();
                DbProject dbProject = new DbProject();
                System.Diagnostics.Debug.WriteLine(
                    "DbNotification - InsertNotification: ProjectsController Created");

                dbProject.InsertProject(typeUuid);

                // SECOND insert the notification.
                notification.projectUuid = typeUuid;
                lock (DbContext.locker)
                {
                    Db.Insert(notification);
                }
                //THIRD: async get extra minimum info for the notification list.
                pc.UpdateProjectFromServer(typeUuid);
            }
            System.Diagnostics.Debug.WriteLine("DbNotification - InsertNotification: Test: End of method");
        }
        public List<object> GetNotificationListProjectOnly()
        {
            DbNotification db = new DbNotification();
            DbProject dbProject = new DbProject();
            IEnumerable<Notification> notifications = db.GetNotifications();
            List<object> notificationList = new List<object>();
            foreach (var n in notifications)
            {
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.id = " + n.id);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.jobUuid = " + n.jobUuid);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.projectUuid = " + n.projectUuid);

                if (!string.IsNullOrWhiteSpace(n.projectUuid))
                {
                    Project project = dbProject.GetProjectByUuid(n.projectUuid);
                    project.companies = dbProject.GetAllCompaniesRelatedToProject(project);
                    notificationList.Add(project);
                }
            }
            return notificationList;
        }