/// <summary>
        /// Gets all StudyGroups from the servers REST Api.
        /// </summary>
        public async Task UpdateStudyGroupsFromServer()
        {
            DbStudyGroup db = new DbStudyGroup();
            System.Diagnostics.Debug.WriteLine("StudyGroupsController - GetStudyGroupsFromServer: initiated");
            DbStudent dbStudent = new DbStudent();
            string accessToken = dbStudent.GetStudentAccessToken();

            if (accessToken == null)
            {
                Authenticater.Authorized = false;
                return;
            }

            Uri url = new Uri(Adress);
            System.Diagnostics.Debug.WriteLine("StudyGroupsController - url " + url.ToString());
            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
            try
            {
                var response = await client.GetAsync(url);
                if (response.StatusCode == HttpStatusCode.OK) {
                    System.Diagnostics.Debug.WriteLine("GetStudyGroupsFromServer response " + response.StatusCode.ToString());
                    var results = await response.Content.ReadAsAsync<IEnumerable<StudyGroup>>();
                    db.DeleteAllStudyGroups();

                    foreach (var studygroup in results)
                    {
                        // ugly gui filter hack
                        studygroup.filterChecked = false;
                        db.InsertStudyGroup(studygroup);
                    }
                }
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    Authenticater.Authorized = false;
                }
            }

            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("StudyGroupsController - GetStudyGroupsFromServer: await client.GetAsync(\"url\") Failed");
                System.Diagnostics.Debug.WriteLine("StudyGroupsController - GetStudyGroupsFromServer: Exception msg: " + e.Message);
                System.Diagnostics.Debug.WriteLine("StudyGroupsController - GetStudyGroupsFromServer: Stack Trace: \n" + e.StackTrace);
                System.Diagnostics.Debug.WriteLine("StudyGroupsController - GetStudyGroupsFromServer: End Of Stack Trace");
            }
        }
        public void SaveSettings()
        {
            //DbLocation lc = new DbLocation();
            //DbCourse cc = new DbCourse();
            //if (cs == true)
            //{
                DbStudyGroup sgc = new DbStudyGroup();

                foreach (fagområdeSetting setting in oppgaveSettings)
                {
                    //gets the name and setting from 
                    string setName = setting.Name;
                    bool setSwitch = setting.IsSelected;

                    foreach (var studygroup in studyGroupsFilter)
                    {
                        if (studygroup.name == setName)
                        {
                            studygroup.name = setName;
                            studygroup.filterChecked = setSwitch;
                            break;
                        }
                    }
                }
                sgc.UpdateStudyGroups(studyGroupsFilter);
            //    cs = false; //set changedsetting to false after saving
            //    CarouselOppgaver.pullList = true; //set pullList to true, meaning that any refresh action will reload the list according to new settings
            //}
        }
        private void GetAllFilters()//object sender, EventArgs e
        {
            //DbLocation lc = new DbLocation();
            //DbCourse cc = new DbCourse();
            DbStudyGroup sgc = new DbStudyGroup();
            //DbJobType jtc = new DbJobType();
            //List<Location> locationsGet = lc.GetAllLocations();
            //List<Course> coursesGet = cc.GetAllCourses();
            studyGroupsFilter = sgc.GetAllStudyGroups();
            //List<JobType> jobTypesJobGet = jtc.GetJobTypeFilterJob();
            //List<JobType> jobTypesProjectGet = jtc.GetJobTypeFilterProject();

            foreach (var studyGroup in studyGroupsFilter)
            {
                studyDict.Add(studyGroup.name, studyGroup.id);
            }

            //locationsFilter.Add(new Location(TODO)); //add empty location for default "nothing selected"
            //foreach (var location in locationsGet)
            //{
            //    locationsFilter.Add(location);
            //}
            //Course velgEmne = new Course();
            //velgEmne.name = "Velg emne";
            //coursesSettings.Add(velgEmne);
            //foreach (var course in coursesGet)
            //{
            //    coursesSettings.Add(course);
            //}

            // for jobs
            // DbLocation.UpdateLocations(List<Location>) sett max 1 til TRUE !
            // for projects
            // DbCourse.UpdateCourses(List<Course> courses) sett max 1 til TRUE !
            // for all
            // DbJobTypes.UpdateJobTypes(List<JobType> jobTypes) sett max 1 til TRUE !
            //
            // DbStudyGroup.UpdateStudyGroups(List<StudyGroup> studyGroups) 
        }
        /// <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>
        /// Deseriliazes a singular Jobs with childrem. 
        /// This method is not fully completed and should be used with caution.
        /// </summary>
        /// <param name="jsonString">Serialized data contain information about job and its children</param>
        /// <returns>A deserialized Jobs object</returns>
        private Job Deserialize(string jsonString)
        {
            DbJob db = new DbJob();
            Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
            System.Diagnostics.Debug.WriteLine("DeserializeApiData. Printing Key Value:");

            string[] keys = dict.Keys.ToArray();

            Job j = new Job();
            j.companies = new List<Company>();
            j.jobTypes = new List<JobType>();
            j.locations = new List<Location>();
            j.studyGroups = new List<StudyGroup>();           

            CompaniesController cp = new CompaniesController();

            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"))
                {
                    j.uuid = dict[key].ToString();
                }
                if (key.Equals("title"))
                {
                    j.title = dict[key].ToString();
                }

                if (key.Equals("description"))
                {
                    j.description = dict[key].ToString();
                }
                
                if (key.Equals("webpage"))
                {
                    j.webpage = dict[key].ToString();
                }

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

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

                if (key.Equals("companies"))
                {
                    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("DeserializeOneJobs: company.id: " + company.id);
                        j.companies.Add(company);
                        dbCompany.UpdateCompany(company);
                        System.Diagnostics.Debug.WriteLine("DeserializeOneJobs: After j.companies.Add(company)");
                        string jobUuid = dict["uuid"].ToString();
                        dbCompany.InsertCompanyJob(company.id, jobUuid);
                    }
                }

                if (key.Equals("studyGroups"))
                {
                    IEnumerable studyGroups = (IEnumerable)dict[key];
                    //Newtonsoft.Json.Linq.JArray'
                    System.Diagnostics.Debug.WriteLine("studyGroups created");
                    DbStudyGroup dbStudyGroup = new DbStudyGroup();
                    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();
                        }

                        j.studyGroups.Add(sg);

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

                    }
                }

                if (key.Equals("locations"))
                {
                    IEnumerable locations = (IEnumerable)dict[key];
                    //Newtonsoft.Json.Linq.JArray'
                    DbLocation dbLocation = new DbLocation();
                    System.Diagnostics.Debug.WriteLine("location created");
                    foreach (var location in locations)
                    {
                        System.Diagnostics.Debug.WriteLine("foreach initiated");
                        Dictionary<string, object> locationDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(location.ToString());
                        Location loc = new Location();
                        if (locationDict.ContainsKey("id"))
                        {
                            
                            loc.id = locationDict["id"].ToString();
                            System.Diagnostics.Debug.WriteLine("location id: " + loc.id);
                        }

                        if (locationDict.ContainsKey("name"))
                        {
                            loc.name = locationDict["name"].ToString();
                        }

                        dbLocation.InsertLocation(loc);
                        j.locations.Add(loc);
                        string jobUuid = dict["uuid"].ToString();
                        dbLocation.InsertLocationJob(loc.id, jobUuid);
                    }
                }


                if (key.Equals("jobTypes"))
                {
                    IEnumerable jobTypes = (IEnumerable)dict[key];
                    //Newtonsoft.Json.Linq.JArray'
                    DbJobType dbJobType = new DbJobType();
                    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 j.jobTypes.Add(jt);");
                        j.jobTypes.Add(jt);

                        string jobUuid = dict["uuid"].ToString();
                        dbJobType.InsertJobTypeJob(jt.id, jobUuid);
                    }
                }
            }
            db.UpdateJob(j);
            return j;
        }
        private async void GetAllFilters(object sender, EventArgs e)
        {
            DbLocation lc = new DbLocation();
            DbCourse cc = new DbCourse();
            DbStudyGroup sgc = new DbStudyGroup();
            DbJobType jtc = new DbJobType();
            List<Location> locationsFilter = lc.GetAllLocations();
            List<Course> coursesFilter = cc.GetAllCourses();
            List<StudyGroup> studyGroupsFilter = sgc.GetAllStudyGroups();
            List<JobType> jobTypesJobFilter = jtc.GetJobTypeFilterJob();
            List<JobType> jobTypesProjectFilter = jtc.GetJobTypeFilterProject();

            System.Diagnostics.Debug.WriteLine("GetAllFilters: locationsFilter.Count: " + locationsFilter.Count);
            System.Diagnostics.Debug.WriteLine("GetAllFilters: coursesFilter.Count: " + coursesFilter.Count);
            System.Diagnostics.Debug.WriteLine("GetAllFilters: studyGroupsFilter.Count: " + studyGroupsFilter.Count);
            System.Diagnostics.Debug.WriteLine("GetAllFilters: jobTypesJobFilter.Count: " + jobTypesJobFilter.Count);
            System.Diagnostics.Debug.WriteLine("GetAllFilters: jobTypesProjectFilter.Count: " +
                                               jobTypesProjectFilter.Count);
        }
        public void SaveSettings()
        {
            //DbLocation lc = new DbLocation();
            //DbCourse cc = new DbCourse();
            //if (cs == true)
            //{
                DbStudyGroup sgc = new DbStudyGroup();

                foreach (fagområdeSetting setting in varslerSettings)
                {
                    //gets the name and setting from 
                    string setName = setting.Name;
                    bool setSwitch = setting.IsSelected;

                    foreach (StudyGroup studygroup in studyGroupsFilter)
                    {
                        if (studygroup.name == setName)
                        {
                            studygroup.name = setName;
                            studygroup.filterChecked = setSwitch;
                            break;
                        }
                    }
                }
                sgc.UpdateStudyGroups(studyGroupsFilter);
                //cs = false;
            //}
        }
        public async Task GetAllFilters()
        {

            DbStudyGroup sgc = new DbStudyGroup();
            StudentsController sc = new StudentsController();

            studyGroupsFilter = sgc.GetAllStudyGroups(); //set checked to false
            List<StudyGroup> checkedStudyGroups = await sc.GetStudentsStudyGroupFromServer(); // use these to check some to true

            System.Diagnostics.Debug.WriteLine("studyGroupsFilter.Count: " + studyGroupsFilter.Count); 
            foreach (var sg in studyGroupsFilter)
            {
                if (checkedStudyGroups.Contains(sg))
                {
                    sg.filterChecked = true;
                }

                else
                {
                     sg.filterChecked = false;
                }
                //studyGroupsFilter.Add(sg);
            }
            System.Diagnostics.Debug.WriteLine("Another studyGroupsFilter.Count: " + studyGroupsFilter.Count);
            foreach (var studyGroup in studyGroupsFilter)
            {
                studyDict.Add(studyGroup.name, studyGroup.id);
            }
        }
 private string CreateLocalHash()
 {
     DbStudyGroup db = new DbStudyGroup();
     List<StudyGroup> studyGroups = db.GetAllStudyGroups();
     StringBuilder sb = new StringBuilder();
     foreach (var sg in studyGroups)
     {
         
         sb.Append(Hasher.Base64Decode(sg.id));
     }
     return Hasher.CalculateMd5Hash(sb.ToString());
 }
        /// <summary>
        /// Extracts the StudyGroup ids from a json string, then builds a list from those ids by querying the local database. 
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        private List<StudyGroup> ExtractStudyGroupsFromJson(string jsonString)
        {
            Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
            System.Diagnostics.Debug.WriteLine("DeserializeApiData. Printing Key Value:");

            string[] keys = dict.Keys.ToArray();
            List<StudyGroup> studyGroupList = new List<StudyGroup>();

            DbStudyGroup dbStudyGroup = new DbStudyGroup();

            foreach (var key in keys)
            {
                System.Diagnostics.Debug.WriteLine("key: " + key);
                System.Diagnostics.Debug.WriteLine("value: " + dict[key].ToString());

                if (key.Equals("studyGroups"))
                {
                    IEnumerable studyGroups = (IEnumerable)dict[key];
                    foreach (var studyGroup in studyGroups)
                    {
                        Dictionary<string, object> studyGroupDict =
                            JsonConvert.DeserializeObject<Dictionary<string, object>>(studyGroup.ToString());

                        string id = studyGroupDict["id"].ToString();
                        studyGroupList.Add(dbStudyGroup.GetStudygroup(Hasher.Base64Encode(id)));
                    }
                    return studyGroupList;
                }
            }
            return null;
        }
 void GetAllFilters()
 {
     DbStudyGroup sgc = new DbStudyGroup();
     studyGroupsFilter = sgc.GetAllStudyGroups();
     
     foreach (var studyGroup in studyGroupsFilter)
     {
         studyDict.Add(studyGroup.name, studyGroup.id);
     }
 }