/// <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>
        /// 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());
        }
        private async void TestInsertJob(object sender, EventArgs e)
        {
            DbContext DbContext = DbContext.GetDbContext;
            SQLiteConnection Db = DbContext.Db;

            System.Diagnostics.Debug.WriteLine("Before insert Job.Count: " +
                                               Db.Query<Job>("Select * from Job").Count());

            JobsController jc = new JobsController();
            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
            };

            // try catch on tables that will not be affected by a job delete
            try
            {
                Db.Insert(comp);
            }
            catch
            {
            }
            Db.Insert(job);
            try
            {
                Db.Insert(loc);
            }
            catch
            {
            }
            try
            {
                Db.Insert(sg);
            }
            catch
            {
            }
            Db.Insert(sgj);
            Db.Insert(lj);
            Db.Insert(cj);
            try
            {
                Db.Insert(jt);
            }
            catch
            {
            }
            Db.Insert(jtj);

            System.Diagnostics.Debug.WriteLine("After insert: Job.Count: " +
                                               Db.Query<Job>("Select * from Job").Count());

        }
        private async void TestJobsFilterWeb_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 vestagder = Hasher.Base64Encode("vestagder");
            string heltid = Hasher.Base64Encode("heltid");
            filter.Add("locations", vestagder);
            filter.Add("types", heltid);

            JobsController jc = new JobsController();
            IEnumerable<Job> jobs = await jc.GetJobsBasedOnFilter(studyGroups, filter);

            if (!Authenticater.Authorized)
            {
                GoToLogin();
            }
            if (jobs != null)
            {
                System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter: jobs.Count(): " +
                                                   jobs.Count());
                foreach (var job in jobs)
                {
                    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);
                }
            }
        }
      /*
            NotificationsController nc = new NotificationsController();
            ProjectsController pc = new ProjectsController();
            JobsController jc = new JobsController();

            IEnumerable<Notification> notifications = nc.GetNotifications();

            var sb = new StringBuilder();

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

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

                    Job j = jc.GetJobByUuid(n.jobUuid);
                    List<Company> jCompanies = jc.GetAllCompaniesRelatedToJob(j);

                    System.Diagnostics.Debug.WriteLine(
                    "ViktorTestView - NotificationsFromDb_OnClicked: companies.Count = " + jCompanies.Count());
                    j.companies = jCompanies;
                    System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var n.projectUuid = " + n.projectUuid);
                    System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var p.uuid = " + j.uuid);
                    System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var p.title = " + j.title);
                    System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var p.webpage = " + j.webpage);
                    System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: p.companies.Count = " + j.companies.Count);

                    try
                    {
                        System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var p.companies[0].name = " + j.companies[0].name);
                        System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var p.companies[0].logo " + j.companies[0].logo);

                        var text = string.Format("title: {0}, company: {1}, published: {2}, webpage: {3}, logo: {4}, expiryDate: {5}",
                            j.title, j.companies[0].name, j.published,
                            j.webpage, j.companies[0].logo, j.expiryDate);


                        //job.companies.Select(c => new { c.id }));
                        sb.AppendLine(text);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: Exception msg: " + ex.Message);
                        System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: Stack Trace: \n" + ex.StackTrace);
                        System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: End Of Stack Trace");
                    }

                }

                else
                {
                    Project p = pc.GetProjectByUuid(n.projectUuid);
                    List<Company> pCompanies = pc.GetAllCompaniesRelatedToProject(p);
                    System.Diagnostics.Debug.WriteLine(
                        "ViktorTestView - NotificationsFromDb_OnClicked: companies.Count = " + pCompanies.Count());
                    p.companies = pCompanies;
                    System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var n.projectUuid = " + n.projectUuid);
                    System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var p.uuid = " + p.uuid);
                    System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var p.title = " + p.title);
                    System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var p.webpage = " + p.webpage);
                    System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: p.companies.Count = " + p.companies.Count);
        
                    try
                    {
                        System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var p.companies[0].name = " + p.companies[0].name);
                        System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: var p.companies[0].logo " + p.companies[0].logo);

                        //var text = string.Format("title: {0}, published: {1}, webpage: {2}", p.title,  p.published, p.webpage);
                        
                        var text = string.Format("title: {0}, company: {1}, published: {2}, webpage: {3}, logo: {4}",
                            p.title, p.companies[0].name, p.published,
                            p.webpage, p.companies[0].logo);
                        //job.companies.Select(c => new { c.id }));
                        
                        sb.AppendLine(text);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: Exception msg: " + ex.Message);
                        System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: Stack Trace: \n" + ex.StackTrace);
                        System.Diagnostics.Debug.WriteLine("ViktorTestView - NotificationsFromDb_OnClicked: End Of Stack Trace");
                    }
                } 

             


            }
            TextBox.Text = sb.ToString();
            }
            */
        private async void GetAllJobsFromWebApi_OnClicked(object sender, EventArgs e)
        {
            JobsController jc = new JobsController();
            IEnumerable<Job> jobs = await jc.GetJobsBasedOnFilter();
            if (!Authenticater.Authorized)
            {
                GoToLogin();
            }
            if (jobs != null)
            {
                System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter: jobs.Count(): " +
                                                   jobs.Count());
            }
        }
        private async Task AddData()
        {
            //Dictionary<string, string> filter = new Dictionary<string, string>(); //contains only one item from each group
            //filter.Add("courses", "DAT-304");
            //filter.Add("types", "virksomhet");

            //if (pullList == false)
            //{
            //}
            //else if (pullList == true)
            //{
            JobsController jc = new JobsController();

            IEnumerable<Job> jobs = await jc.GetJobsBasedOnFilter(LISTINIT.GetSettings(), null);

            HashSet<Job> newJobs = new HashSet<Job>(jobs);
            HashSet<Job> oldJobs = new HashSet<Job>(JOBS);
            bool sameJobs = newJobs.SetEquals(oldJobs);

            if (!sameJobs) {
                StillingList.ItemsSource = null;
                JOBS.Clear();
                foreach (Job p in jobs)
                {
                    //JOBS.Clear();
                    JOBS.Add(p);
                }
                Sort(sort);
                //StillingList.ItemsSource = JOBS;
            }

            if (!Authenticater.Authorized)
                {
                    GoToLogin();
                }

            //    pullList = false;
            //}
        }
        /// <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");
        }