//public bool CancelRequest(string sharepointUrl, string accessToken,string hosturl,string apponlytoken, string status)
        public bool CancelRequest(SharePointContext spContext, string status)
      //  public bool CancelRequest( string status)
        {
            Microsoft.SharePoint.Client.ListItemCollection listItems;
          // using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl, accessToken))
            if(spContext==null)
              spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb())
            {

                try
                {
                    //if (this.StartDate > DateTime.Now)
                    //{
                    Web web = clientContext.Web;
                    ListCollection lists = web.Lists;
                    List selectedList = lists.GetByTitle("TimeOffRequests");
                    clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                    clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                    clientContext.ExecuteQuery();

                    CamlQuery camlQuery = new CamlQuery();
                    StringBuilder camlwhere = new StringBuilder();
                    camlwhere.Append("<Where>");
                    camlwhere.Append("<Eq><FieldRef Name='RequestID'/><Value Type='Text'>" + this.RequestID + "</Value></Eq>");
                    camlwhere.Append("</Where>");
                    camlQuery.ViewXml = @"<View><Query>" + camlwhere.ToString() + "</Query></View>";
                    listItems = selectedList.GetItems(camlQuery);
                    clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();

                    string concernApprover = "";

                    foreach (Microsoft.SharePoint.Client.ListItem oListItem in listItems)
                    {
                        if (status == "Approved")
                        {
                            if (oListItem["ID"] != null)
                            {
                                Microsoft.SharePoint.Client.ListItem listItem = selectedList.GetItemById(Convert.ToInt32(oListItem["ID"].ToString()));
                                //  var app1 = oListItem["Approver1"] as Microsoft.SharePoint.Client.FieldLookupValue;
                                //var app2 = oListItem["Approver2"] as Microsoft.SharePoint.Client.FieldLookupValue;
                                //var app3 = oListItem["Approver3"] as Microsoft.SharePoint.Client.FieldLookupValue;

                                //var status1 = oListItem["Approver1Status"] as string;
                                //var status2 = oListItem["Approver2Status"] as string;
                                //var status3 = oListItem["Approver3Status"] as string;

                                //if (status1 != "")                                    
                                //    concernApprover = app1.ToString();                                  
                                //if (status2 != "")
                                //    concernApprover = app2.ToString();
                                //if (status3 != "")                                 
                                //    concernApprover = app3.ToString();
                                // concernApprover = app1.ToString();
                                //Send an Cancellation email to approver1
                                //update "CancelStatus"
                                if (oListItem["Approver1"] == null)  // if there is no Approvers
                                {
                                    // listItem.DeleteObject();//implemented in workflow
                                    listItem["CancelStatus"] = "Cancel";
                                    listItem.Update();
                                    // Delete from calendar

                                    try
                                    {

                                        string deptCalName = Config.DepartmentCalendar;//default from web.config
                                        //Get from App Config (custom)
                                        ConfigListValues objConfAppList = new ConfigListValues();
                                        objConfAppList.GetConfigValues(spContext);
                                        if (objConfAppList.items != null)
                                        {
                                            if (objConfAppList.items["DepartmentCalendar"] != null)
                                            {
                                                deptCalName = objConfAppList.items["DepartmentCalendar"].ToString();
                                            }
                                        }


                                        DeptCalendar obj = new DeptCalendar();
                                        string requestorName = oListItem["RequestedBy"] as Microsoft.SharePoint.Client.FieldLookupValue == null ? "" : (oListItem["RequestedBy"] as Microsoft.SharePoint.Client.FieldLookupValue).LookupValue;
                                        string type = oListItem["TimeOffType"].ToString() == null ? "UnAssigned" : oListItem["TimeOffType"].ToString();
                                        obj.Title = requestorName + "-" + type;
                                        DateTime startDate = (DateTime)oListItem["StartDateTime"];
                                        obj.EventTime = startDate;

                                        // obj.DeleteEvent(hosturl, apponlytoken, deptCalName);
                                        obj.DeleteEvent(deptCalName, spContext);
                                    }
                                    catch
                                    {
                                    }

                                }
                                else
                                {
                                    listItem["CancelStatus"] = "Cancel";
                                    listItem.Update();
                                }
                            }
                        }
                        else
                        {
                            Microsoft.SharePoint.Client.ListItem listItem = selectedList.GetItemById(Convert.ToInt32(oListItem["ID"].ToString()));

                            listItem["CancelStatus"] = "Cancel";
                            listItem.Update();

                            //listItem.DeleteObject(); //implemented in workflow


                        }
                    }

                    clientContext.ExecuteQuery();

                    // }
                }

                catch (Exception ex)
                {
                    Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                    clientContext.ExecuteQuery();
                  
                }

                return true;
            }
        }
        public List<TimeOffRequests> GetRequestDetailsStatus(SharePointContext spContext,string year, Dictionary<string, CamlPara> FilterParameters = null, DateTime? startdate = null, DateTime? enddate = null)
        {
            Microsoft.SharePoint.Client.ListItemCollection listItems;
            List<TimeOffRequests> listTimeoffReq = new List<TimeOffRequests>();
            List<string> listyear = new List<string>();
          //  using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl, accessToken))
            if (spContext == null)
                spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb())
            {
                try{
                Web web = clientContext.Web;
                ListCollection lists = web.Lists;
                List selectedList = lists.GetByTitle("TimeOffRequests");
                clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                clientContext.ExecuteQuery();
                CamlQuery camlQuery = new CamlQuery();
                StringBuilder camlwhere = new StringBuilder();
                //camlwhere.Append("<Where><And>");
                //camlwhere.Append("<And><Geq>");
                //camlwhere.Append("<FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + year + "-01-01 00:00:00</Value>");
                //camlwhere.Append("</Geq>");
                //camlwhere.Append("<Leq>");
                //camlwhere.Append("<FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + year + "-12-31 00:00:00</Value>");
                //camlwhere.Append("</Leq></And>");

                //camlwhere.Append("<Eq>");
                //camlwhere.Append("<FieldRef Name='Status' />");
                //camlwhere.Append("<Value Type='Text'>");
                //camlwhere.Append(FilterParameters["Status"].value);
                //camlwhere.Append("</Value>");
                //camlwhere.Append("</Eq></And>");

                //camlwhere.Append("</Where>");

                camlwhere.Append("<Where>");
                camlwhere.Append("<And>");
                camlwhere.Append("     <And>");
                camlwhere.Append("          <And>");
                if (startdate != null && enddate != null)
                {
                    camlwhere.Append("               <Geq><FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + startdate.Value.Year.ToString() + "-" + startdate.Value.Month.ToString() + "-" + startdate.Value.Day.ToString() + " " + startdate.Value.Hour.ToString() + ":" + startdate.Value.Minute + ":00</Value></Geq>");
                    camlwhere.Append("               <Leq><FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + enddate.Value.Year.ToString() + "-" + enddate.Value.Month.ToString() + "-" + enddate.Value.Day.ToString() + " " + enddate.Value.Hour.ToString() + ":" + enddate.Value.Minute + ":00</Value></Leq>");
                }
                else
                {
                    camlwhere.Append("               <Geq><FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + year + "-01-01 00:00:00</Value></Geq>");
                    camlwhere.Append("               <Leq><FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + year + "-12-31 00:00:00</Value></Leq>");
                }
                camlwhere.Append("         </And>");
                camlwhere.Append("                <Eq> <FieldRef Name='Status' /><Value Type='Text'>"+FilterParameters["Status"].value+"</Value></Eq>");
                camlwhere.Append("      </And>");
                camlwhere.Append("       <Neq><FieldRef Name='CancelStatus' /><Value Type='Text'>Cancel</Value></Neq>");
                camlwhere.Append("</And>");
                camlwhere.Append("</Where>");


                string viewFields = "";// "<ViewFields><FieldRef Name='IsFullDay' /><FieldRef Name='TotalHours' /><FieldRef Name='RequestedBy' /><FieldRef Name='TimeOffType' /><FieldRef Name='Status' /></ViewFields>";
                camlQuery.ViewXml = @"<View><Query>" + camlwhere.ToString() + "</Query>" + viewFields + "</View>";
                listItems = selectedList.GetItems(camlQuery);
                clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                clientContext.ExecuteQuery();
                TimeOffRequests objTimeOffRequests;
                foreach (Microsoft.SharePoint.Client.ListItem oListItem in listItems)
                {
                    objTimeOffRequests = new TimeOffRequests();
                    objTimeOffRequests.isFullDay = oListItem["IsFullDay"].ToString() == "True" ? "Full Day" : "Parital day";
                    objTimeOffRequests.TimeOffType = oListItem["TimeOffType"].ToString() == null ? "UnAssigned" : oListItem["TimeOffType"].ToString();
                    objTimeOffRequests.TotalHours = oListItem["TotalHours"].ToString() == null ? 0 : Convert.ToDecimal(oListItem["TotalHours"].ToString());
                    objTimeOffRequests.Status = oListItem["Status"].ToString() == null ? "" : oListItem["Status"].ToString();
                    var arr = oListItem["RequestedBy"] as Microsoft.SharePoint.Client.FieldLookupValue;
                    objTimeOffRequests.RequestedByID = arr == null ? 0 : arr.LookupId;
                    objTimeOffRequests.RequestedBy = arr == null ? "UnAssigned" : arr.LookupValue.ToString();

                    objTimeOffRequests.StartDate = DateTime.Parse(oListItem["StartDateTime"].ToString());
                    objTimeOffRequests.EndDate = DateTime.Parse(oListItem["EndDateTime"].ToString());
                    objTimeOffRequests.IsAccessible = (bool)oListItem["IsAccessible"];
                    objTimeOffRequests.Alternate = (bool)oListItem["HasAlternateContact"];

                    var docType = oListItem["Approver1"] as Microsoft.SharePoint.Client.FieldLookupValue;
                    if (docType != null)
                    {
                        objTimeOffRequests.Approver1 = docType == null ? "UnAssigned" : docType.LookupValue;
                        objTimeOffRequests.Approver1Id = docType == null ? 0 : docType.LookupId;
                    }
                    docType = oListItem["Approver2"] as Microsoft.SharePoint.Client.FieldLookupValue;
                    if (docType != null)
                    {
                        objTimeOffRequests.Approver2 = docType == null ? "UnAssigned" : docType.LookupValue;
                        objTimeOffRequests.Approver2Id = docType == null ? 0 : docType.LookupId;
                    }
                    docType = oListItem["Approver3"] as Microsoft.SharePoint.Client.FieldLookupValue;
                    if (docType != null)
                    {
                        objTimeOffRequests.Approver3 = docType == null ? "UnAssigned" : docType.LookupValue;
                        objTimeOffRequests.Approver3Id = docType == null ? 0 : docType.LookupId;
                    }


                    listTimeoffReq.Add(objTimeOffRequests);
                }
            }
                catch (Exception ex)
                    {
                        Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                        clientContext.ExecuteQuery();
                        
                    }
            }
            return listTimeoffReq;
        }
        public bool DeleteRequest(SharePointContext spContext, string forcedelete = "0")
        {
            Microsoft.SharePoint.Client.ListItemCollection listItems;
            // using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl, accessToken))
            if (spContext == null)
                spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb())
            {
                try
                {
                    Web web = clientContext.Web;
                    ListCollection lists = web.Lists;
                    List selectedList = lists.GetByTitle("TimeOffRequests");
                    clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                    clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                    clientContext.ExecuteQuery();

                    CamlQuery camlQuery = new CamlQuery();
                    StringBuilder camlwhere = new StringBuilder();
                    camlwhere.Append("<Where>");
                    camlwhere.Append("<Eq><FieldRef Name='RequestID'/><Value Type='Text'>" + this.RequestID + "</Value></Eq>");
                    camlwhere.Append("</Where>");
                    camlQuery.ViewXml = @"<View><Query>" + camlwhere.ToString() + "</Query></View>";
                    listItems = selectedList.GetItems(camlQuery);
                    clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();

                    foreach (Microsoft.SharePoint.Client.ListItem oListItem in listItems)
                    {
                        if (oListItem["ID"] != null)
                        {
                            Microsoft.SharePoint.Client.ListItem listItem = selectedList.GetItemById(Convert.ToInt32(oListItem["ID"].ToString()));

                            if (forcedelete == "0")
                            {
                                listItem["CancelStatus"] = "Cancel";
                                listItem.Update();
                            }
                            else
                                listItem.DeleteObject();//implemented in workflow
                        }
                    }
                    clientContext.ExecuteQuery();
                    return true;
                }

                catch (Exception ex)
                {
                    Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                    clientContext.ExecuteQuery();
                    return false;
                }

            }
        }
        public Microsoft.SharePoint.Client.ListItemCollection GetItemByReqID(SharePointContext spContext)
        {
            Microsoft.SharePoint.Client.ListItemCollection listItems;
            if (spContext == null)
                spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb()) // CreateAppOnlyClientContextForSPAppWeb throwing err
            {
                try
                {
                    Web web = clientContext.Web;
                    ListCollection lists = web.Lists;
                    List selectedList = lists.GetByTitle("TimeOffRequests");
                    clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                    clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                    clientContext.ExecuteQuery();

                    CamlQuery camlQuery = new CamlQuery();
                    StringBuilder camlwhere = new StringBuilder();
                    camlwhere.Append("<Where>");
                    //camlwhere.Append("<And>");
                    camlwhere.Append("<Eq><FieldRef Name='RequestID'/><Value Type='Text'>" + this.RequestID + "</Value></Eq>");
                    // camlwhere.Append("<Eq><FieldRef Name='CancelStatus'/><Value Type='Text'>Cancel</Value></Eq>");
                    //camlwhere.Append("</And>");
                    camlwhere.Append("</Where>");
                    camlQuery.ViewXml = @"<View><Query>" + camlwhere.ToString() + "</Query></View>";
                    listItems = selectedList.GetItems(camlQuery);
                    clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();
                    return listItems;
                }
                catch (Exception ex)
                {
                    Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                    clientContext.ExecuteQuery();
                    return null;
                }
            }
        }
        public Dictionary<string, string> GetConfigDetails(SharePointContext spContext)
        {
            Dictionary<string, string> ConfigDetails = new Dictionary<string, string>();
            Microsoft.SharePoint.Client.ListItemCollection listItems;
           // using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken))
            if(spContext==null)
             spContext =    SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb()) // CreateAppOnlyClientContextForSPAppWeb throwing err
            {
                try
                {
                    Web web = clientContext.Web;
                    ListCollection lists = web.Lists;
                    List selectedList = lists.GetByTitle(WebConfigurationManager.AppSettings["ConfigList"]);
                    clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                    clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                    clientContext.ExecuteQuery();

                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = @"<View><Query><Where><IsNotNull><FieldRef Name='ID' /></IsNotNull></Where></Query><FieldRef Name='Key' /><FieldRef Name='Values' /></View>";
                    listItems = selectedList.GetItems(camlQuery);
                    clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();
                    if (listItems == null || listItems.Count == 0)
                        return null;
                    else
                    {
                        foreach (Microsoft.SharePoint.Client.ListItem oListItem in listItems)
                        {
                            ConfigDetails.Add(oListItem["Key"].ToString(), oListItem["Values"].ToString());
                        }
                    }
                }
                catch (Exception ex)
                {                    
                    Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                    clientContext.ExecuteQuery();
                }
            }
            return ConfigDetails;
        }