/// <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();
        }
        public List<object> GetNotificationListJobOnly()
        {
            DbJob dbJob = new DbJob();
            DbNotification db = new DbNotification();
            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);
                if (!string.IsNullOrWhiteSpace(n.jobUuid))
                {

                    Job job = dbJob.GetJobByUuid(n.jobUuid);
                    job.companies = dbJob.GetAllCompaniesRelatedToJob(job);
                    notificationList.Add(job);
                }
            }
            return notificationList;
        }
        /// <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;
        }
        /// <summary>
        /// Can return 3 different values:
        /// 1. "exists": No new jobs on the server. 
        /// 2. "incorrectCache": If the cache indicates that local database got data that the server doesnt have. 
        /// 3. "newData": There are new jobs 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.
        /// TODO Way to complicated logic, simplify this method if theres time
        /// </summary>
        /// <returns></returns>
        private async Task<string> CheckServerForNewData(List<string> studyGroups = null, Dictionary<string, string> filter = null)
        {
            //"api/v1/jobs/lastmodifed"
            string queryParams = CreateQueryParams(studyGroups, null, filter);
            string adress = Adress + "/" + "lastmodified" + queryParams;
            System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData - adress: " + adress);
            Uri url = new Uri(adress);
            System.Diagnostics.Debug.WriteLine("JobController - 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("JobController - 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("JobsController - 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("JobController - CheckServerForNewData: await client.GetAsync(\"url\") Failed");
                System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: Exception msg: " + e.Message);
                System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: Stack Trace: \n" + e.StackTrace);
                System.Diagnostics.Debug.WriteLine("JobController - 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("amountOfJobs"))
                {
                    string uuid = dict["uuid"].ToString();
                    DateTime dateTime = (DateTime)dict["modified"];
                    long modified = long.Parse(dateTime.ToString("yyyyMMddHHmmss"));
                    string uuids = dict["hash"].ToString();
                    int amountOfJobs = 0;
                    try
                    {
                        amountOfJobs = Int32.Parse(dict["amountOfJobs"].ToString());
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: await client.GetAsync(\"url\") Failed");
                        System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: Exception msg: " + ex.Message);
                        System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: Stack Trace: \n" + ex.StackTrace);
                        System.Diagnostics.Debug.WriteLine("JobController - CheckServerForNewData: End Of Stack Trace");
                        return null;
                    }
                    DbJob db = new DbJob();
                    bool existInDb = db.ExistsInDb(uuid, modified);
                    if (!existInDb)
                    {
                        return "newData";
                        //return existInDb;
                    }
                    var localJobs = db.GetJobsFromDbBasedOnFilter(studyGroups, filter, true);
                    int localDbCount = localJobs.Count();

                    StringBuilder sb = new StringBuilder();
                    foreach (var job in localJobs)
                    {
                        sb.Append(job.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 (amountOfJobs > localDbCount)
                        {
                            return "newData"; 
                            //return !existInDb;
                        }
                        return "incorrectCache";
                    }
                    return "exists";
                    //return existInDb;
                }
            }
            return null;
        }
        /// <summary>
        /// Gets a job based on optional filters.
        /// </summary>
        /// <param name="studyGroups">studyGroups can be a list of numerous studygroups ex: helse, idrettsfag, datateknologi </param>
        /// </param>
        /// <param name="filter">A dictionary where key can be: titles (values:title of the job), types (values: deltid, heltid, etc...),
        ///                      locations (values: vestagder, austagder), . 
        ///                      Supports only 1 key at this current implementation!</param>
        /// <returns></returns>
        public async Task<IEnumerable<Job>> GetJobsBasedOnFilter(List<string> studyGroups = null,
             Dictionary<string, string> filter = null)
        {
            DbJob db = new DbJob();
            //string adress = "http://kompetansetorgetserver1.azurewebsites.net/api/v1/jobs";
            string instructions = await CheckServerForNewData(studyGroups, filter);
            if (!Authenticater.Authorized)
            {
                return null;
            }
            if (instructions != null)
            {
                System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter - instructions: " + instructions);
                if (instructions == "exists")  // "newData"; incorrectCache exists
                {
                    IEnumerable<Job> filteredJobs = db.GetJobsFromDbBasedOnFilter(studyGroups, filter);
                    filteredJobs = db.GetAllCompaniesRelatedToJobs(filteredJobs.ToList());
                    return filteredJobs;
                }
            }

            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("GetJobsBasedOnFilter - url: " + url.ToString());
            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

            string jsonString = null;
            IEnumerable<Job> jobs = null;
            try
            {
                var response = await client.GetAsync(url).ConfigureAwait(false);
                System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter 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();
                    //DeleteJobs(GetJobsFromDbBasedOnFilter(studyGroups, filter));
                    if (instructions != null && instructions == "incorrectCache")
                    {
                        var cachedJobs = db.GetJobsFromDbBasedOnFilter(studyGroups, filter);
                        jobs = DeserializeMany(jsonString);
                        // Get all jobs from that local dataset that was not in the data set provided by the server
                        // These are manually deleted jobs and have to be cleared from cache.
                        // linear search is ok because of small data set
                        var manuallyDeletedJobs = cachedJobs.Where(j => !jobs.Any(cj2 => cj2.uuid == j.uuid));
                        db.DeleteObsoleteJobs(manuallyDeletedJobs.ToList());
                    }
                    else
                    {
                        jobs = DeserializeMany(jsonString);
                    }

                }

                else
                {
                    System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter - Using the local database");
                    jobs = db.GetJobsFromDbBasedOnFilter(studyGroups, filter);
                    jobs = db.GetAllCompaniesRelatedToJobs(jobs.ToList());
                }
                return jobs;
            }
            catch (Exception e)
            {
                // Hack workaround if mobil data and wifi is turned off
                try
                {
                    jobs = db.GetJobsFromDbBasedOnFilter(studyGroups, filter);
                    jobs = db.GetAllCompaniesRelatedToJobs(jobs.ToList());
                    return jobs;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("JobsController - GetJobsBasedOnFilter: await client.GetAsync(\"url\") Failed");
                    System.Diagnostics.Debug.WriteLine("JobsController - GetJobsBasedOnFilter: Exception msg: " + ex.Message);
                    System.Diagnostics.Debug.WriteLine("JobsController - GetJobsBasedOnFilter: Stack Trace: \n" + ex.StackTrace);
                    System.Diagnostics.Debug.WriteLine("JobsController - GetJobsBasedOnFilter: End Of Stack Trace");
                    System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter - Using the local database");
                    return null;
                }
            }
        }
        /// <summary>
        /// This test method require that you have not logged in and got no authorization
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void TestDeleteExpiredJobs(object sender, EventArgs e)
        {
            DbJob jc = new DbJob();

            DbContext DbContext = DbContext.GetDbContext;
            SQLiteConnection Db = DbContext.Db;

            DateTime yesterday = DateTime.Now.AddDays(-1);
            long n = long.Parse(yesterday.ToString("yyyyMMddHHmmss"));

            string testUuid = "colemak";
            Job job = new Job()
            {
                uuid = testUuid,
                expiryDate = n
            };

            string companyId = "Ikea";
            Company comp = new Company()
            {
                id = companyId
            };

            string locationId = "sverige";
            Location loc = new Location()
            {
                id = locationId
            };

            string sgId = "dykking";
            StudyGroup sg = new StudyGroup()
            {
                id = sgId
            };

            StudyGroupJob sgj = new StudyGroupJob()
            {
                StudyGroupId = sgId,
                JobUuid = testUuid
            };

            LocationJob lj = new LocationJob()
            {
                LocationId = locationId,
                JobUuid = testUuid
            };

            CompanyJob cj = new CompanyJob()
            {
                CompanyId = companyId,
                JobUuid = testUuid
            };

            string jtId = "10aarErfaringEcma6";
            JobType jt = new JobType()
            {
                id = jtId
            };

            JobTypeJob jtj = new JobTypeJob()
            {
                JobUuid = testUuid,
                JobTypeId = jtId
            };

            Db.Insert(comp);
            Db.Insert(job);
            Db.Insert(loc);
            Db.Insert(sg);
            Db.Insert(sgj);
            Db.Insert(lj);
            Db.Insert(cj);
            Db.Insert(jt);
            Db.Insert(jtj);

            Job j = Db.Get<Job>(testUuid);
            System.Diagnostics.Debug.WriteLine("j.expiryDate: " + j.expiryDate);
            System.Diagnostics.Debug.WriteLine("StudyGroup.Count: " +
                                               Db.Query<StudyGroup>("Select * from StudyGroup").Count());
            System.Diagnostics.Debug.WriteLine("Job.Count: " +
                                               Db.Query<Job>("Select * from Job").Count());
            System.Diagnostics.Debug.WriteLine("JobType.Count: " +
                                               Db.Query<JobType>("Select * from JobType").Count());
            System.Diagnostics.Debug.WriteLine("Location.Count: " +
                                               Db.Query<Location>("Select * from Location").Count());
            System.Diagnostics.Debug.WriteLine("Company.Count: " +
                                               Db.Query<Company>("Select * from Company").Count());

            System.Diagnostics.Debug.WriteLine("CompanyJob.Count: " +
                                               Db.Query<CompanyJob>("Select * from CompanyJob").Count());
            System.Diagnostics.Debug.WriteLine("JobTypeJob.Count: " +
                                               Db.Query<JobTypeJob>("Select * from JobTypeJob").Count());
            System.Diagnostics.Debug.WriteLine("LocationJob.Count: " +
                                               Db.Query<LocationJob>("Select * from LocationJob").Count());
            System.Diagnostics.Debug.WriteLine("StudyGroupJob.Count: " +
                                               Db.Query<StudyGroupJob>("Select * from StudyGroupJob").Count());

            System.Diagnostics.Debug.WriteLine("Time for delete");
            jc.DeleteAllExpiredJobs();
            System.Diagnostics.Debug.WriteLine("Job.Count: " +
                                               Db.Query<Job>("Select * from Job").Count());
            System.Diagnostics.Debug.WriteLine("CompanyJob.Count: " +
                                               Db.Query<CompanyJob>("Select * from CompanyJob").Count());
            System.Diagnostics.Debug.WriteLine("JobTypeJob.Count: " +
                                               Db.Query<JobTypeJob>("Select * from JobTypeJob").Count());
            System.Diagnostics.Debug.WriteLine("LocationJob.Count: " +
                                               Db.Query<LocationJob>("Select * from LocationJob").Count());
            System.Diagnostics.Debug.WriteLine("StudyGroupJob.Count: " +
                                               Db.Query<StudyGroupJob>("Select * from StudyGroupJob").Count());
            //CompanyJobs, StudyGroupJob, LocationJob og JobTypeJob.

        }
        /// <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 TestJobsFilterDb_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);

            Dictionary<string, string> filter = new Dictionary<string, string>();
            string vestagder = Hasher.Base64Encode("vestagder");
            string heltid = Hasher.Base64Encode("heltid");
            filter.Add("locations", vestagder);
            filter.Add("types", heltid);


            DbJob jc = new DbJob();
            var jobs = jc.GetJobsFromDbBasedOnFilter(null, filter);

            if (jobs == null)
            {
                System.Diagnostics.Debug.WriteLine("TestJobsFilterDb:  was null aka failed!");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter: jobs.Count(): " +
                                                   jobs.Count());

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

                    }
                }
            }

            var jobs2 = jc.GetJobsFromDbBasedOnFilter(studyGroups);

            if (jobs2 == null)
            {
                System.Diagnostics.Debug.WriteLine("TestJobsFilterDb:  was null aka failed!");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter: jobs2.Count(): " +
                                                   jobs2.Count());

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

            var jobs3 = jc.GetJobsFromDbBasedOnFilter(studyGroups, filter);

            if (jobs3 == null)
            {
                System.Diagnostics.Debug.WriteLine("TestJobsFilterDb:  was null aka failed!");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter: jobs3.Count(): " +
                                                   jobs3.Count());

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

                    }
                }
            }

            Dictionary<string, string> filter2 = new Dictionary<string, string>();
            //string internship = Hasher.Base64Encode("Internship");
            filter2.Add("titles", "Internship");

            var jobs4 = jc.GetJobsFromDbBasedOnFilter(studyGroups, filter2);

            if (jobs4 == null)
            {
                System.Diagnostics.Debug.WriteLine("TestJobsFilterDb:  was null aka failed!");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter: jobs4.Count(): " +
                                                   jobs4.Count());

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

                    }
                }
            }
            /*
            StudyGroupsController sgc = new StudyGroupsController();
            sgc.UpdateStudyGroupsFromServer(); */
        }
        /// <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");
        }
Пример #10
0
 private void DeleteOutdatedData()
 {
     DbJob dbJob = new DbJob();
     dbJob.DeleteAllExpiredJobs();
 }