/// <summary>
 /// Assigns the loan resource details.
 /// </summary>
 /// <param name="presenter">The presenter.</param>
 private void AssignLoanResourceDetails(TeamLeavesPresenter presenter)
 {
     var teamMembers = this.developerService.RetrieveList(SessionData.Instance.UserInfo.Developer.DeveloperID, null, SessionData.Instance.UserInfo.Developer.DeveloperID);
     presenter.AssignTeamMembersList(teamMembers);
     var supervisors = this.developerService.RetrieveList(null, null, SessionData.Instance.UserInfo.Developer.DeveloperID);
     presenter.AssignSupervisorsList(supervisors.Where(s => s.DeveloperID != SessionData.Instance.UserInfo.Developer.DeveloperID).ToList());
 }
        /// <summary>
        /// Loads the leave counts.
        /// </summary>
        /// <param name="leavesPresenter">The leaves presenter.</param>
        private void LoadLeaveCounts(TeamLeavesPresenter leavesPresenter)
        {
            this.AddFilterTypes(leavesPresenter);

            var fromeDate = leavesPresenter.IsMonthView ? Convert.ToDateTime(leavesPresenter.FromDate).RetrieveCurrentMonthStartDate() : Convert.ToDateTime(leavesPresenter.FromDate).RetrieveCurrentYearStartDate();
            var toDate = leavesPresenter.IsMonthView ? Convert.ToDateTime(leavesPresenter.ToDate).RetrieveCurrentMonthEndDate() : Convert.ToDateTime(leavesPresenter.ToDate).RetrieveCurrentYearEndDate();

            IList<LeaveCalendarCounts> leaveCountsList = this.leaveService.LoadLeaveCalendarCounts(leavesPresenter.TeamMember.DeveloperID, leavesPresenter.SelectedDeveloperIds, leavesPresenter.SelectedProjectIds, fromeDate, toDate, !leavesPresenter.IsMonthView, SessionData.Instance.UserInfo.Developer.DeveloperID, leavesPresenter.SelectedFiltersIds);
            if (leaveCountsList != null)
            {
                for (int count = 0; count < leaveCountsList.Count; count++)
                {
                    if (count == 0)
                    {
                        leavesPresenter.LeaveCounts = leaveCountsList[count].LeaveCount.HasValue ? leaveCountsList[count].LeaveCount.Value.ToString("0.#") : leaveCountsList[count].LeaveCount.ToString();
                    }
                    else
                    {
                        leavesPresenter.LeaveCounts = leaveCountsList[count].LeaveCount.HasValue ? string.Format(CultureInfo.CurrentCulture, "{0},{1:0.#}", leavesPresenter.LeaveCounts, leaveCountsList[count].LeaveCount.Value) : string.Format(CultureInfo.CurrentCulture, "{0},{1}", leavesPresenter.LeaveCounts, leaveCountsList[count].LeaveCount);
                    }
                }
            }
        }
        /// <summary>
        /// Adds the filter types.
        /// </summary>
        /// <param name="leavesPresenter">The leaves presenter.</param>
        private void AddFilterTypes(TeamLeavesPresenter leavesPresenter)
        {
            string filterIds = string.Empty;
            var filtersArray = leavesPresenter.FilterType.Split(',');
            for (int i = 0; i < leavesPresenter.FilterDataList.Count; i++)
            {
                if (filtersArray.Contains(leavesPresenter.FilterDataList[i].FilterType))
                {
                    if (leavesPresenter.FilterDataList[i].FilterId.HasValue)
                    {
                        filterIds = leavesPresenter.FilterDataList[i].FilterId.Value + "," + filterIds;
                    }
                }
            }

            leavesPresenter.SelectedFiltersIds = filterIds.Remove(filterIds.Length - 1);
        }
        /// <summary>
        /// Sets the developer list.
        /// </summary>
        /// <param name="presenter">The presenter.</param>
        private void SetDeveloperList(TeamLeavesPresenter presenter)
        {
            IList<DeveloperListItem> developerList = null;
            if (SessionUserManager.IsUserHR() && SessionData.Instance.UserInfo.Developer.DeveloperID.Equals(presenter.TeamMember.DeveloperID))
            {
                developerList = this.developerService.RetrieveList(null, null, SessionData.Instance.UserInfo.Developer.DeveloperID);
                var user = developerList.Where(dev => dev.DeveloperID.Equals(presenter.TeamMember.DeveloperID)).FirstOrDefault();

                if (user != null)
                {
                    developerList.Remove(user);
                }

                presenter.HasTeam = this.developerService.RetrieveList(Convert.ToInt32(presenter.TeamMember.DeveloperID, CultureInfo.CurrentCulture), null, SessionData.Instance.UserInfo.Developer.DeveloperID).Count > 0;
            }
            else
            {
                developerList = this.developerService.RetrieveList(Convert.ToInt32(presenter.TeamMember.DeveloperID, CultureInfo.CurrentCulture), null, SessionData.Instance.UserInfo.Developer.DeveloperID);
                presenter.HasTeam = true;
            }

            presenter.DevelopersList(developerList);
        }
        /// <summary>
        /// Initializes the presenter.
        /// </summary>
        /// <param name="leavesPresenter">The leaves presenter.</param>
        /// <param name="filterType">Type of the filter.</param>
        private static void InitializePresenter(TeamLeavesPresenter leavesPresenter, string filterType)
        {
            AssignSelectedProjectIds(leavesPresenter);
            AssignSelectedDeveloperIds(leavesPresenter);

            leavesPresenter.FilterType = !string.IsNullOrEmpty(filterType) ? filterType : Pending;

            if (leavesPresenter.SelectedDate == DateTime.MinValue)
            {
                leavesPresenter.SelectedDate = DateTime.Now;
                leavesPresenter.CurrentMonth = DateTime.Now.ToString(MonthNumberFormat, CultureInfo.InvariantCulture);
            }
        }
        /// <summary>
        /// Initializes the filter data.
        /// </summary>
        /// <param name="leavesPresenter">The leaves presenter.</param>
        private static void InitializeFilterData(TeamLeavesPresenter leavesPresenter)
        {
            if (string.IsNullOrEmpty(leavesPresenter.FilterType))
            {
                leavesPresenter.FilterType = string.IsNullOrEmpty(leavesPresenter.FilterType) ? Pending : leavesPresenter.FilterType;
            }

            var filtersArray = leavesPresenter.FilterType.Split(',');
            IList<FilterData> filterData = new List<FilterData>();
            filterData.Add(new FilterData { FilterType = Approved, FilterId = 1, IsSelected = filtersArray.Contains(All) || filtersArray.Contains(Approved) });
            filterData.Add(new FilterData { FilterType = FilterCanceled, FilterId = 4, IsSelected = filtersArray.Contains(All) || filtersArray.Contains(FilterCanceled) });
            filterData.Add(new FilterData { FilterType = Pending, FilterId = 0, IsSelected = filtersArray.Contains(All) || filtersArray.Contains(Pending) });
            filterData.Add(new FilterData { FilterType = FilterRejected, FilterId = 2, IsSelected = filtersArray.Contains(All) || filtersArray.Contains(FilterRejected) });
            filterData.Add(new FilterData { FilterType = FilterRevoked, FilterId = 3, IsSelected = filtersArray.Contains(All) || filtersArray.Contains(FilterRevoked) });
            leavesPresenter.AssignFilterDataList(filterData);
        }
        /// <summary>
        /// Assigns the selected developer ids.
        /// </summary>
        /// <param name="presenter">The team leaves presenter.</param>
        private static void AssignSelectedDeveloperIds(TeamLeavesPresenter presenter)
        {
            IList<int> developerIds = new List<int>();
            if (string.IsNullOrEmpty(presenter.SelectedDeveloperIds))
            {
                developerIds = presenter.DeveloperList.Select(id => id.DeveloperID).ToList();
            }
            else
            {
                developerIds =
                    presenter.SelectedDeveloperIds.Split(',')
                        .Select(id => Convert.ToInt32(id, CultureInfo.CurrentCulture))
                        .ToList();
            }

            presenter.AssignSelectedDeveloperList(developerIds);
        }
        /// <summary>
        /// Initializes the filter.
        /// </summary>
        /// <param name="presenter">The team leaves presenter.</param>
        /// <param name="selectedProject">The selected project.</param>
        /// <param name="selectedDeveloper">The selected developer.</param>
        private static void InitializeFilter(TeamLeavesPresenter presenter, string selectedProject, string selectedDeveloper)
        {
            if (string.IsNullOrWhiteSpace(presenter.FilterType))
            {
                presenter.FilterType = Pending;
            }

            if (string.IsNullOrEmpty(selectedProject) && string.IsNullOrEmpty(selectedDeveloper))
            {
                presenter.SelectedProjectIds = string.Join(",", presenter.MasterProjects.Select(s => s.ProjectID).ToList());
                presenter.SelectedDeveloperIds = string.Join(",", presenter.DeveloperList.Select(d => d.DeveloperID).ToList());
            }
            else
            {
                presenter.SelectedProjectIds = selectedDeveloper;
                presenter.SelectedDeveloperIds = selectedProject;
            }
        }
        /// <summary>
        /// Gets the team leaves developer list.
        /// </summary>
        /// <param name="presenter">The team leaves presenter.</param>
        /// <returns>Developer List</returns>
        public ActionResult GetTeamLeavesDeveloperList(TeamLeavesPresenter presenter)
        {
            if (presenter != null && presenter.DeveloperList != null)
            {
                IList<int> developerIds = new List<int>();
                developerIds = presenter.DeveloperList.Select(item => item.DeveloperID).ToList();
                presenter.AssignSelectedDeveloperList(developerIds);
                presenter.SelectedDeveloperIds = string.Join(",", developerIds);
            }

            return this.Json(presenter);
        }
        /// <summary>
        /// Assigns the selected project ids.
        /// </summary>
        /// <param name="presenter">The team leaves presenter.</param>
        private static void AssignSelectedProjectIds(TeamLeavesPresenter presenter)
        {
            IList<int> projectIds = new List<int>();

            if (string.IsNullOrEmpty(presenter.SelectedProjectIds))
            {
                projectIds = presenter.MasterProjects.Select(item => item.ProjectID).ToList();
            }
            else
            {
                projectIds =
                    presenter.SelectedProjectIds.Split(',')
                        .Select(id => Convert.ToInt32(id, CultureInfo.CurrentCulture))
                        .ToList();
            }

            presenter.AssignSelectedProjectList(projectIds);
        }
        /// <summary>
        /// Gets the Team Leaves project list.
        /// </summary>
        /// <param name="presenter">The team leaves presenter.</param>
        /// <returns>Project List</returns>
        public ActionResult GetTeamLeavesProjectList(TeamLeavesPresenter presenter)
        {
            if (presenter != null && presenter.MasterProjects != null)
            {
                IList<int> projectIds = new List<int>();
                projectIds = presenter.MasterProjects.Select(item => item.ProjectID).ToList();
                presenter.AssignSelectedProjectList(projectIds);
                presenter.SelectedProjectIds = string.Join(",", projectIds);
            }

            return this.Json(presenter);
        }
        /// <summary>
        /// Retrieves the leave request.
        /// </summary>
        /// <param name="leaveId">The leave identifier.</param>
        /// <param name="presenter">The team leaves presenter.</param>
        /// <returns>Team Leave Status Partial View</returns>
        public ActionResult RetrieveLeaveRequest(string leaveId, TeamLeavesPresenter presenter)
        {
            ModelState.Clear();
            if (presenter != null)
            {
                var userId = SessionUserManager.IsUserHR() ? SessionData.Instance.UserInfo.Developer.DeveloperID : presenter.TeamMember.DeveloperID;
                var leaveData = this.leaveService.GetLeave(Convert.ToInt32(leaveId, CultureInfo.CurrentCulture), userId);
                var developerListItem = presenter.DeveloperList.FirstOrDefault(a => a.DeveloperID == leaveData.DeveloperId);
                if (developerListItem != null)
                {
                    var loginId = developerListItem.LoginID;
                    presenter.DeveloperImageUrl = loginId.ToString(CultureInfo.CurrentCulture).RetrieveDeveloperImageName();
                }
                else
                {
                    presenter.DeveloperImageUrl = leaveData.DeveloperId.ToString(CultureInfo.CurrentCulture).RetrieveDeveloperImageName();
                }

                if (leaveData != null)
                {
                    presenter.LeaveData = leaveData;
                    int caseSwitch = presenter.LeaveData.Status;
                    switch (caseSwitch)
                    {
                        case 0:
                            presenter.LeaveStatus = Resources.PendingApproval;
                            break;

                        case 1:
                            presenter.LeaveStatus = Resources.Approved;
                            break;

                        case 2:
                            presenter.LeaveStatus = Resources.Rejected;
                            break;

                        case 3:
                            presenter.LeaveStatus = Resources.Revoked;
                            break;

                        case 4:
                            presenter.LeaveStatus = Resources.Cancelled;
                            break;

                        case 5:
                            presenter.LeaveStatus = Resources.RequestedAgain;
                            break;
                    }
                }
            }

            return this.PartialView(TeamLeaveStatusPartialView, presenter);
        }
        /// <summary>
        /// Updates the team leave status.
        /// </summary>
        /// <param name="presenter">The presenter.</param>
        /// <param name="buttonName">Name of the button.</param>
        /// <param name="comment">The comment.</param>
        /// <returns>Empty String.</returns>
        public JsonResult UpdateTeamLeaveStatus(
            TeamLeavesPresenter presenter,
            string buttonName,
            string comment)
        {
            ModelState.Clear();
            if ((presenter != null) && !string.IsNullOrEmpty(buttonName))
            {
                byte status = (byte)LeaveStatus.Pending;
                bool isEscalate = false;
                bool isRequestAgain = false;

                int modifiedBy = presenter.TeamMember.DeveloperID;

                if (buttonName.Equals(Cancel, StringComparison.OrdinalIgnoreCase))
                {
                    status = (byte)LeaveStatus.Canceled;
                    modifiedBy = SessionUserManager.IsUserHR() ? SessionData.Instance.UserInfo.Developer.DeveloperID : modifiedBy;
                }
                else if (buttonName.Equals(Approve, StringComparison.OrdinalIgnoreCase))
                {
                    status = (byte)LeaveStatus.Approved;
                }
                else if (buttonName.Equals(Reject, StringComparison.OrdinalIgnoreCase))
                {
                    status = (byte)LeaveStatus.Rejected;
                }
                else if (buttonName.Equals(Escalate, StringComparison.OrdinalIgnoreCase))
                {
                    status = (byte)LeaveStatus.Pending;
                    isEscalate = true;
                    modifiedBy = SessionUserManager.IsUserHR() ? SessionData.Instance.UserInfo.Developer.DeveloperID : modifiedBy;
                }

                var comments = !string.IsNullOrEmpty(comment) ? comment : string.Empty;

                var currentLeaveStatus = this.leaveService.UpdateStatus(presenter.LeaveData.LeaveId, status, comments, presenter.TeamMember.DeveloperID, isEscalate, isRequestAgain, presenter.LeaveData.Status, (byte)ApplicationType.Website);
                if (currentLeaveStatus != null && currentLeaveStatus.Count > 0)
                {
                    var approvedLeaves = string.Empty;
                    var dateDayTypeText = string.Empty;

                    if (currentLeaveStatus.Any(leave => leave.Date != DateTime.MinValue))
                    {
                        currentLeaveStatus.ForEach(leave =>
                        {
                            dateDayTypeText = leave.DateDayType == (byte)LeaveDateDayType.FirstHalfLeave ? (Resources.HistoryOpeningBracket + Resources.FirstHalfLeave + Resources.ClosingBracket) : (leave.DateDayType == (byte)LeaveDateDayType.SecondHalfLeave ? (Resources.HistoryOpeningBracket + Resources.SecondHalfLeave + Resources.ClosingBracket) : string.Empty);
                            approvedLeaves += string.Format(CultureInfo.CurrentCulture, "{0} {1}, ", leave.Date.Value.ToString(MonthDateFormat, CultureInfo.CurrentCulture), dateDayTypeText);
                        });

                        approvedLeaves = approvedLeaves.Remove(approvedLeaves.LastIndexOf(','));

                        approvedLeaves = currentLeaveStatus.Count == 1 ? string.Format(CultureInfo.CurrentCulture, Resources.LeaveAlreadyApproved, approvedLeaves) : string.Format(CultureInfo.CurrentCulture, Resources.LeavesAlreadyApplied, approvedLeaves);
                    }
                    else
                    {
                        var leaveStatus = currentLeaveStatus.FirstOrDefault();
                        if (leaveStatus != null)
                        {
                            approvedLeaves = leaveStatus.Status.ToString();
                        }
                    }

                    return this.Json(approvedLeaves);
                    ////return this.Json(currentLeaveStatus);
                }
            }

            return this.Json(string.Empty);
        }
        public ActionResult Index(TeamLeavesPresenter leavesPresenter, string filterType)
        {
            if (SessionUserManager.IsUserHR() || this.developerService.RetrieveList(leavesPresenter.TeamMember.DeveloperID, null, SessionData.Instance.UserInfo.Developer.DeveloperID).Count() > 0)
            {
                this.AddBreadcrumbItem(Resources.Assignments, Url.AssignmentsAction());
            }

            this.AddBreadcrumbItem(string.Format(CultureInfo.CurrentCulture, CommonUrlFormat, Resources.TeamMemberDashboard, leavesPresenter.TeamViewType), Url.TeamDashboardAction());
            leavesPresenter.TeamMember = this.developerService.RetrieveByDeveloperId(leavesPresenter.TeamMember.DeveloperID, SessionData.Instance.UserInfo.Developer.DeveloperID);
            leavesPresenter.TeamMember.DeveloperImage = leavesPresenter.TeamMember.LoginID.RetrieveDeveloperImageName();
            InitializePresenter(leavesPresenter, leavesPresenter.FilterType);
            var teamList = this.developerService.RetrieveList(SessionData.Instance.UserInfo.Developer.DeveloperID, null, SessionData.Instance.UserInfo.Developer.DeveloperID);
            if (teamList.Count > 0)
            {
                teamList.Add(SessionData.Instance.UserInfo.Developer);
            }

            var result = teamList.Where(a => a.DeveloperID == leavesPresenter.TeamMember.DeveloperID).ToList();
            if (result.Count > 0)
            {
                leavesPresenter.IsUnderHierarchy = true;
            }

            InitializeFilterData(leavesPresenter);
            this.LoadLeaveCounts(leavesPresenter);

            this.AssignLoanResourceDetails(leavesPresenter);

            return this.View(leavesPresenter);
        }
        /// <summary>
        /// Indexes the specified filter type.
        /// </summary>
        /// <param name="developerId">The developer identifier.</param>
        /// <param name="filterType">Type of the filter.</param>
        /// <returns>
        /// Team Leaves view
        /// </returns>
        public ActionResult Index(string developerId, string filterType)
        {
            TeamLeavesPresenter presenter = new TeamLeavesPresenter();
            if (presenter != null)
            {
                presenter.TeamMember = string.IsNullOrWhiteSpace(developerId) ? SessionData.Instance.UserInfo.Developer : this.developerService.RetrieveByDeveloperId(Convert.ToInt32(developerId, CultureInfo.CurrentCulture), SessionData.Instance.UserInfo.Developer.DeveloperID);
                var teamList = this.developerService.RetrieveList(SessionData.Instance.UserInfo.Developer.DeveloperID, null, SessionData.Instance.UserInfo.Developer.DeveloperID);
                if (teamList.Count <= 0 && !SessionUserManager.IsUserHR())
                {
                    return this.Redirect(Url.MyLeavesAction());
                }

                if (presenter.TeamMember.DeveloperID != SessionData.Instance.UserInfo.Developer.DeveloperID && !SessionUserManager.IsUserHR() && teamList.Count == 0)
                {
                    return this.Redirect(Url.TeamLeavesAction());
                }
                else
                {
                    if (SessionUserManager.IsUserHR() || this.developerService.RetrieveList(SessionData.Instance.UserInfo.Developer.DeveloperID, null, SessionData.Instance.UserInfo.Developer.DeveloperID).Count() > 0)
                    {
                        this.AddBreadcrumbItem(Resources.Assignments, Url.AssignmentsAction());
                    }

                    presenter.TeamViewType = TeamViewType.Leaves;
                    this.AddBreadcrumbItem(string.Format(CultureInfo.CurrentCulture, CommonUrlFormat, Resources.TeamMemberDashboard, presenter.TeamViewType), Url.TeamDashboardAction());
                    presenter.TeamMember.DeveloperImage = presenter.TeamMember.LoginID.RetrieveDeveloperImageName();
                    presenter.AssignDevelopers(SessionData.Instance.AllDevelopers);
                    presenter.SelectedDate = DateTimeHelper.RetrieveCurrentDateTime();
                    var selectedProject = presenter.SelectedProjectIds;
                    var selectedDeveloper = presenter.SelectedDeveloperIds;
                    var projectsList = this.lookupService.RetrieveProjects(null, null, false, null, SessionData.Instance.UserInfo.Developer.DeveloperID);
                    presenter.AssignMasterProjects(projectsList.Sort());

                    this.SetDeveloperList(presenter);
                    AssignSelectedProjectIds(presenter);
                    AssignSelectedDeveloperIds(presenter);
                    presenter.CurrentMonth = DateTime.Now.ToString(MonthNumberFormat, CultureInfo.InvariantCulture);

                    var holidays = this.lookupService.RetrieveHolidays(DateTime.Now.Year, SessionData.Instance.UserInfo.Developer.DeveloperID).Select(holiday => holiday.Date.ToString(MonthDateFormat, CultureInfo.CurrentCulture)).ToList();
                    for (int count = 0; count < holidays.Count; count++)
                    {
                        if (count == 0)
                        {
                            presenter.Holidays = holidays[count];
                        }
                        else
                        {
                            presenter.Holidays = string.Format(CultureInfo.CurrentCulture, "{0},{1}", presenter.Holidays, holidays[count]);
                        }
                    }

                    var leaveTypes = this.lookupService.RetrieveLeaveTypes(SessionData.Instance.UserInfo.Developer.DeveloperID).ToList();
                    presenter.AssignLeaveTypes(leaveTypes);

                    var leaveDayTypes = this.lookupService.RetrieveLeaveDayTypes(SessionData.Instance.UserInfo.Developer.DeveloperID).ToList();
                    presenter.AssignLeaveDayTypes(leaveDayTypes);
                    presenter.FilterType = !string.IsNullOrEmpty(filterType) ? filterType : Pending;
                    InitializeFilter(presenter, selectedProject, selectedDeveloper);
                    var fromDate = DateTime.Now.RetrieveCurrentYearStartDate();
                    var toDate = DateTime.Now.RetrieveCurrentYearEndDate();
                    presenter.FromDate = fromDate.ToString();
                    presenter.ToDate = toDate.ToString();
                    this.AssignLoanResourceDetails(presenter);
                    if (teamList.Count > 0)
                    {
                        teamList.Add(SessionData.Instance.UserInfo.Developer);
                    }

                    var result = teamList.Where(a => a.DeveloperID == presenter.TeamMember.DeveloperID).ToList();
                    if (result.Count > 0)
                    {
                        presenter.IsUnderHierarchy = true;
                    }

                    IList<FilterData> filterData = new List<FilterData>();
                    filterData.Add(new FilterData { FilterType = All, IsSelected = false });
                    filterData.Add(new FilterData { FilterType = Approved, IsSelected = false });
                    filterData.Add(new FilterData { FilterType = Pending, IsSelected = true });
                    presenter.AssignFilterDataList(filterData);
                    InitializeFilterData(presenter);
                    this.LoadLeaveCounts(presenter);
                }
            }

            return this.View(presenter);
        }