//
        // GET: /EmailSchedulers/Create

        public ActionResult Create()
        {
            ViewBag.PossibleProjects = unitOfWork.ProjectRepository.All; //context.Projects;
            EmailScheduler emailScheduler = new EmailScheduler();

            //IEnumerable<ScheduleType> scheduleTypes = Enum.GetValues(typeof(ScheduleType)).Cast<ScheduleType>();

            emailScheduler.SchedulerTitles = from item in unitOfWork.EmailSchedulerRepository.GetSchedulerList()
                                             select new SelectListItem
                                             {
                                                 Text = item.Value,
                                                 Value = item.Key
                                             };

            emailScheduler.ScheduleType = from item in unitOfWork.EmailSchedulerRepository.GetSchedulerTypeAll()
                                          select new SelectListItem
                                          {
                                              Text = item.Value,
                                              Value = item.Key
                                          };

            var recipientTypes = unitOfWork.EmailSchedulerRepository.GetRecipientUserTypeAll();
                //new Dictionary<string, string> {{ "0", "--- Select recipient users ---" }, 
                                                                //{ "1", "Task's Users" }, 
                                                                //{ "2", "Task's Followers" },
                                                                //{ "3", "Task's Users & Followers" },
                                                                // { "4", "Project's Users" }};

            emailScheduler.EmailRecipientUsers = from item in recipientTypes
                                                 select new SelectListItem
                                                 {
                                                     Text = item.Value,
                                                     Value = item.Key
                                                 };

            emailScheduler.Days = from item in unitOfWork.EmailSchedulerRepository.GetDaysOfWeek()
                                  select new SelectListItem
                                  {
                                      Text = item.Value,
                                      Value = item.Key
                                  };

            //IEnumerable<Week> days = Enum.GetValues(typeof(Week)).Cast<Week>();
            //emailScheduler.Days = from action in days
            //                      select new SelectListItem
            //                      {
            //                          Text = action.ToString(),
            //                          Value = ((int)action).ToString()
            //                      };

            //emailScheduler.ScheduledTime = new TimeSpan(11, 30, 0);

            //emailScheduler.ScheduledTime = new TimeSpan(15, 30, 0);

            emailScheduler.ScheduledDate = DateTime.Today;

            //String testDt = DateTime.Now.ToShortTimeString();

            //String testDt = DateTime.Now.ToString("hh:mm tt");

            //emailScheduler.ScheduledTime = Convert.ToDateTime(DateTime.Now.ToString("hh:mm tt"));

            emailScheduler.ScheduledTime = DateTime.Now.ToString("hh:mm tt");

            return View(emailScheduler);
        }
        public ActionResult Edit(EmailScheduler emailscheduler)
        {
            emailscheduler.ModifiedBy = (int)Membership.GetUser().ProviderUserKey;
            emailscheduler.ModificationDate = DateTime.Now;

            if (ModelState.IsValid)
            {
                unitOfWork.EmailSchedulerRepository.InsertOrUpdate(emailscheduler);
                unitOfWork.Save();
                return RedirectToAction("Index");
                //context.Entry(emailscheduler).State = System.Data.Entity.EntityState.Modified;
                //context.SaveChanges();
                //return RedirectToAction("Index");
            }

            ViewBag.PossibleProjects = unitOfWork.ProjectRepository.All;
            //ViewBag.PossibleProjects = context.Projects;
            return View(emailscheduler);
        }
        /*
         Send a daily Task Status email to each user having tasks in projects, that are part of Sprints.
         It should be sent on a specific time setat the project level. 
         */
        public List<Mailer> DailyTaskStatus(EmailScheduler objEmailScheduler ) 
        {
            List<Mailer> mailerList = new List<Mailer>();
            List<Task> taskList = unitofWork.TaskRepository.AllIncludingForMail().Where(t => t.ProjectStatus.Name.ToLower() != "closed").ToList();
            //List<UserProfile> userList = unitofWork.UserRepository.All();          

            //string emailbody = "style=\".emailTbl {border: 1px solid #000000;border-radius: 5px;margin: 0;padding: 0;width: 574px;-moz-border-radius-bottomleft:5px;-webkit-border-bottom-left-radius:5px;border-bottom-left-radius:5px;-moz-border-radius-bottomright:5px;-webkit-border-bottom-right-radius:5px;border-bottom-right-radius:5px;-moz-border-radius-topright:5px;-webkit-border-top-right-radius:5px;border-top-right-radius:5px;-moz-border-radius-topleft:5px;-webkit-border-top-left-radius:5px;border-top-left-radius:5px;}.emailTbl table{border-collapse: collapse;border-spacing: 0;width:100%;margin:0px;padding:0px;}.emailTbl tr:last-child td:last-child {-moz-border-radius-bottomright:5px;-webkit-border-bottom-right-radius:5px;border-bottom-right-radius:5px;}.emailTbl table tr:first-child td:first-child {-moz-border-radius-topleft:5px;-webkit-border-top-left-radius:5px;border-top-left-radius:5px;}.emailTbl table tr:first-child td:last-child {-moz-border-radius-topright:5px;-webkit-border-top-right-radius:5px;border-top-right-radius:5px;}.emailTbl tr:last-child td:first-child{-moz-border-radius-bottomleft:5px;-webkit-border-bottom-left-radius:5px;border-bottom-left-radius:5px;}.emailTbl tr:hover td{}.emailTbl tr:nth-child(odd){ background-color:#e8edff; }.emailTbl tr:nth-child(even){background-color:#ffffff; }.emailTbl td{vertical-align:middle;border:1px solid #000000;border-width:0px 1px 1px 0px;text-align:left;padding:9px;font-size:12px;font-family:Arial;font-weight:normal;color:#000000;}.emailTbl tr:last-child td{border-width:0px 1px 0px 0px;}.emailTbl tr td:last-child{border-width:0px 0px 1px 0px;}.emailTbl tr:last-child td:last-child{border-width:0px 0px 0px 0px;}.emailTbl tr:first-child td{background:-o-linear-gradient(bottom, #b9c9fe 5%, #b9c9fe 100%);	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #b9c9fe), color-stop(1, #b9c9fe) );background:-moz-linear-gradient( center top, #b9c9fe 5%, #b9c9fe 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#b9c9fe,endColorstr=#b9c9fe);	background: -o-linear-gradient(top,#b9c9fe,b9c9fe);background-color:#b9c9fe;border:0px solid #000000;text-align:center;border-width:0px 0px 1px 1px;font-size:14px;font-family:Arial;font-weight:bold;color:#000000;}.emailTbl tr:first-child:hover td{background:-o-linear-gradient(bottom, #b9c9fe 5%, #b9c9fe 100%);	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #b9c9fe), color-stop(1, #b9c9fe) );background:-moz-linear-gradient( center top, #b9c9fe 5%, #b9c9fe 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#b9c9fe, endColorstr=#b9c9fe);	background: -o-linear-gradient(top,#b9c9fe,b9c9fe);background-color:#b9c9fe;}.emailTbl tr:first-child td:first-child{border-width:0px 0px 1px 0px;}.emailTbl tr:first-child td:last-child{border-width:0px 0px 1px 1px;}\"";
            //string styleTable     = "style=\"border-collapse: collapse;border-spacing: 0;width: 100%;margin: 0;padding: 0\"";
            //string styleTableRow  = "style=\"background-color: #fff\"";
            //string styleTableData = "style=\"vertical-align: middle;border: 1px solid #000;border-width: 0 1px 1px 0;text-align: left;padding: 9px;font-size: 12px;font-family: Arial;font-weight: normal;color: #000\"";

            List<UserProfile> userList = new List<UserProfile>();

            if (objEmailScheduler.RecipientUserType.Value == 1)             //Task's user
            {
               List<UserProfile> userListByProject = GetAllUserByProjectId(objEmailScheduler.ProjectID);
               userList = userListByProject;
            }
            else if (objEmailScheduler.RecipientUserType.Value == 2)       // Task's Followers
            {
                List<UserProfile> userListByProject = GetAllUserByProjectId(objEmailScheduler.ProjectID);
                userList = userListByProject;
            }
            else if (objEmailScheduler.RecipientUserType.Value == 3)        //Task's Users & Followers
            {
                List<UserProfile> userListByProject = GetAllUserByProjectId(objEmailScheduler.ProjectID);
                userList = userListByProject;
            }
            else if (objEmailScheduler.RecipientUserType.Value == 4)        //Task's Creator & Followers
            {
                List<UserProfile> userListByProject = GetAllUserByProjectId(objEmailScheduler.ProjectID);
                userList = userListByProject;
            }
            else if (objEmailScheduler.RecipientUserType.Value == 5)        //Project's Users
            {
                List<UserProfile> userListByProject = GetAllUserByProjectId(objEmailScheduler.ProjectID);
                userList = userListByProject;
            }

            else if (objEmailScheduler.RecipientUserType.Value == 6)        //Task's Creator & Users
            {
                List<UserProfile> userListByProject = GetAllUserByProjectId(objEmailScheduler.ProjectID);
                userList = userListByProject;
            }

            else if (objEmailScheduler.RecipientUserType.Value == 7)        //Task's Creator & Users
            {
                List<UserProfile> userListByProject = GetAllUserByProjectId(objEmailScheduler.ProjectID);
                userList = userListByProject;
            }


            string styleTableHeader = "style= \"background-color:#0094ff; border:1px solid;\"";
            string styleGroupbyRow = "style= \"background-color:#57C0E1;\"";
            string styleTaskRow = "style= \"background-color:#A0D0FF;\"";

            foreach(UserProfile objOfuser in userList)
            {
                string messageBody = string.Empty;
                List<Task> userTaskList = new List<Task>();
                           
                if (objEmailScheduler.RecipientUserType.Value == 1)  //Task's user
                {
                    userTaskList= taskList.Where(a => a.Users.Any(b => b.UserId == objOfuser.UserId) && a.ProjectID == objEmailScheduler.ProjectID).ToList();
                }

                else if (objEmailScheduler.RecipientUserType.Value == 2)// Task's Followers
                {
                    userTaskList = taskList.Where(a => a.Followers.Any(b => b.UserId == objOfuser.UserId) && a.ProjectID == objEmailScheduler.ProjectID).ToList();
                }

                else if (objEmailScheduler.RecipientUserType.Value == 3) //Task's Users & Followers
                {
                    userTaskList = taskList.Where(a => a.Followers.Any(b => b.UserId == objOfuser.UserId && a.ProjectID == objEmailScheduler.ProjectID) || (a.Users.Any(c => c.UserId == objOfuser.UserId && a.ProjectID == objEmailScheduler.ProjectID))).ToList();
                }
                else if (objEmailScheduler.RecipientUserType.Value == 4) //Task's Creator & Followers
                {
                    userTaskList = taskList.Where((a => a.CreatedBy == objOfuser.UserId && a.ProjectID == objEmailScheduler.ProjectID || a.Followers.Any(b => b.UserId == objOfuser.UserId && a.ProjectID == objEmailScheduler.ProjectID))).ToList();
                }

                else if (objEmailScheduler.RecipientUserType.Value == 5) //Project's Users
                {
                    List<Task> tasklist = unitofWork.TaskRepository.AllTaskByIndividalProject(objEmailScheduler.ProjectID);               
                    userTaskList = tasklist.Where(a => a.Users.Any(b => b.UserId == objOfuser.UserId)).ToList();
                }
                else if (objEmailScheduler.RecipientUserType.Value == 6) //Task's Creator & Users
                {                 
                    userTaskList = taskList.Where((a => a.CreatedByUser == objOfuser && a.ProjectID == objEmailScheduler.ProjectID || a.Users.Any(b => b.UserId == objOfuser.UserId && a.ProjectID==objEmailScheduler.ProjectID))).ToList();
                }

                else if (objEmailScheduler.RecipientUserType.Value == 7) //Task's Creator 
                {                   
                    userTaskList = taskList.Where(a => a.CreatedBy == objOfuser.UserId && a.ProjectID==objEmailScheduler.ProjectID).ToList();
                }

               
                //taskList.Where(a => a.Users.Any(b => b.UserId == objOfuser.UserId) && a.ProjectID == objEmailScheduler.ProjectID).ToList();

                if (userTaskList.Count > 0)
                {
                    messageBody = "<b>Dear &nbsp;" + objOfuser.FirstName + "</b>,<br>" + "<b>Your Daily Tasks Status are given below</b><br>";
                   
                    messageBody += "<table><tr " + styleTableHeader + "><th>Task ID</th> <th>Task Title</th> <th>Task Status</th> <th>Project</th></tr>";

                    foreach (var task in userTaskList)
                    {
                        messageBody += "<tr> ";
                        messageBody += "<td " + styleTaskRow + "> " + task.TaskUID + "</td>";
                        messageBody += "<td " + styleGroupbyRow + "> " + task.Title + "</td>";
                        messageBody += "<td " + styleGroupbyRow + "> " + ((task.ProjectStatus == null) ? " " : task.ProjectStatus.Name) + "</td>";
                        messageBody += "<td " + styleGroupbyRow + "> " + task.Project.Name + "</td>";
                        messageBody += "</tr>";
                    }

                    messageBody += "</table></div><br /><div style='float:left;'><p>We sent you this email because you signed up in PMTool and tasks are assigned to you. <br /> Please don't reply To this mail.</p><p>"
                       + "Regards,<br />PMTool</p></div>";

                    Mailer mailer = new Mailer();
                    mailer.UseMailID = objOfuser.UserName;
                    mailer.MailSubject = "Daily Task Status";
                    mailer.HtmlMailBody = messageBody;
                    mailerList.Add(mailer);
                }
            }

            return mailerList;
        }
        public ActionResult Create(EmailScheduler emailscheduler)
        {
            emailscheduler.CreatedBy = (int)Membership.GetUser(WebSecurity.CurrentUserName).ProviderUserKey;
            emailscheduler.ModifiedBy = (int)Membership.GetUser(WebSecurity.CurrentUserName).ProviderUserKey;
            //timeLog.UserID = (int)Membership.GetUser(WebSecurity.CurrentUserName).ProviderUserKey;
            emailscheduler.CreateDate = DateTime.Now;
            emailscheduler.ModificationDate = DateTime.Now;
            emailscheduler.IsActive = true;

            //emailscheduler.ScheduledTime = new TimeSpan(10, 30, 0);

            if (ModelState.IsValid)
            {
                unitOfWork.EmailSchedulerRepository.InsertOrUpdate(emailscheduler);
                unitOfWork.Save();
                //return RedirectToAction("TaskTimeLog", new { @taskId = timeLog.TaskID, @sprintId = timeLog.SprintID });

                //context.EmailSchedulers.Add(emailscheduler);
                //context.SaveChanges();

                return RedirectToAction("Index");
            }

            ViewBag.PossibleProjects = unitOfWork.ProjectRepository.All; // context.Projects;
            //return View(emailscheduler);
            return RedirectToAction("Index");
        }
        public void InsertOrUpdate(EmailScheduler emailscheduler)
        {
            if (emailscheduler.ID == default(long)) {
                // New entity
                context.EmailSchedulers.Add(emailscheduler);
            } else {
                // Existing entity
                context.Entry(emailscheduler).State = System.Data.Entity.EntityState.Modified;
            }


        }