/// <summary>
        /// approves the league and attaches owners and members to the league.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool ApproveLeague(string id)
        {
            int result = 0;
            try
            {
                Guid leagueId;
                var guidConversion = Guid.TryParse(id, out leagueId);
                if (!guidConversion)
                    return false;

                var dc = new ManagementContext();
                var pendingLeague = dc.LeaguePendings.Include("Creator").Include("Federation").Include("Country").FirstOrDefault(x => x.LeagueId.Equals(leagueId));
                if (pendingLeague == null)
                    return false;

                var contactCard = new DataModels.ContactCard.ContactCard();
                var add = new Address
                {
                    Country = pendingLeague.Country,
                    StateRaw = pendingLeague.StateRaw,
                    CityRaw = pendingLeague.CityRaw,
                    TimeZone = pendingLeague.TimeZone
                };

                var coords = OpenStreetMap.FindLatLongOfAddress(string.Empty, string.Empty, string.Empty, add.CityRaw, add.StateRaw, add.Country != null ? add.Country.Name : string.Empty);
                if (coords != null)
                {
                    add.Coords = new System.Device.Location.GeoCoordinate();
                    add.Coords.Latitude = coords.Latitude;
                    add.Coords.Longitude = coords.Longitude;
                    add.Coords.Altitude = 0;
                    add.Coords.Course = 0;
                    add.Coords.HorizontalAccuracy = 1;
                    add.Coords.Speed = 0;
                    add.Coords.VerticalAccuracy = 1;
                }
                else
                {
                    add.Coords = new System.Device.Location.GeoCoordinate();
                    add.Coords.Latitude = 0.0;
                    add.Coords.Longitude = 0.0;
                    add.Coords.Altitude = 0;
                    add.Coords.Course = 0;
                    add.Coords.HorizontalAccuracy = 1;
                    add.Coords.Speed = 0;
                    add.Coords.VerticalAccuracy = 1;
                }
                contactCard.Addresses.Add(add);

                contactCard.Emails.Add(new RDN.Library.DataModels.ContactCard.Email
                {
                    EmailAddress = pendingLeague.ContactEmail,
                    IsDefault = true
                });


                if (!String.IsNullOrEmpty(pendingLeague.ContactTelephone))
                {
                    var communication = new DataModels.ContactCard.Communication();
                    communication.Data = pendingLeague.ContactTelephone;
                    communication.IsDefault = true;
                    //int comType = Convert.ToInt32(CommunicationTypeEnum.PhoneNumber);
                    //communication.CommunicationType = dc.CommunicationType.Where(x => x.CommunicationTypeId == comType).FirstOrDefault();
                    communication.CommunicationTypeEnum = (byte)CommunicationTypeEnum.PhoneNumber;
                    contactCard.Communications.Add(communication);
                }

                var league = new DataModels.League.League
                {
                    ContactCard = contactCard,
                    Name = pendingLeague.LeagueName,
                    LoweredName = pendingLeague.LeagueName.ToLower(),
                    SubscriptionPeriodEnds = DateTime.UtcNow.AddDays(InvoiceSubscription.NUMBER_OF_DAYS_FOR_TRIAL_SUBSCRIPTION),
                    LeagueJoinCode = Guid.NewGuid(),
                    SubscriptionWillAutoRenew = false

                };


                //we clear it by hitting a URL setup to clear the cache.
                LeagueMember me = new LeagueMember();
                me.League = league;
                me.Member = pendingLeague.Creator;
                me.MembershipDate = DateTime.UtcNow;
                me.LeagueOwnersEnums = (int)LeagueOwnersEnum.Owner;
                league.Members.Add(me);

                if (pendingLeague.Federation != null)
                {
                    FederationLeague l = new FederationLeague();
                    l.Federation = pendingLeague.Federation;
                    l.League = league;
                    l.MembershipDate = DateTime.UtcNow;
                    league.Federations.Add(l);
                }

                //league.Members.Add(pendingLeague.Creator);
                dc.Leagues.Add(league);
                result = dc.SaveChanges();
                pendingLeague.Creator.CurrentLeagueId = league.LeagueId;
                result = dc.SaveChanges();

                //    var result = 1;
                if (result == 0)
                    return false;

                Forum.Forum.CreateNewForum(league.LeagueId, ForumOwnerTypeEnum.league, league.Name + "'s Forum");

                var defaultEmail = pendingLeague.Creator.ContactCard.Emails.FirstOrDefault(x => x.IsDefault.Equals(true));
                if (defaultEmail != null)
                {
                    var emailData = new Dictionary<string, string>();
                    emailData.Add("name", pendingLeague.Creator.Firstname);
                    emailData.Add("derbyname", pendingLeague.Creator.DerbyName);
                    emailData.Add("leaguename", pendingLeague.LeagueName);
                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, defaultEmail.EmailAddress, EmailServer.EmailServer.DEFAULT_SUBJECT + " Your league has been approved", emailData, EmailServer.EmailServerLayoutsEnum.LeagueApproved);
                }

                try
                {
                    WebClient client = new WebClient();
                    client.DownloadStringAsync(new Uri(ServerConfig.URL_TO_CLEAR_MEMBER_CACHE + pendingLeague.Creator.MemberId.ToString()));
                    WebClient client1 = new WebClient();
                    client1.DownloadStringAsync(new Uri(ServerConfig.URL_TO_CLEAR_MEMBER_CACHE_API + pendingLeague.Creator.MemberId.ToString()));
                }
                catch (Exception exception)
                {
                    ErrorDatabaseManager.AddException(exception, exception.GetType());
                }
                dc.LeaguePendings.Remove(pendingLeague);
                result = dc.SaveChanges();

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return result != 0;
        }
        /// <summary>
        /// creates a federation from the current member
        /// </summary>
        /// <param name="nameOfFederation"></param>
        /// <param name="emailAddress"></param>
        /// <param name="phoneNumber"></param>
        /// <param name="owner"></param>
        /// <returns></returns>
        public static DataModels.Federation.Federation CreateFederation(string nameOfFederation, string emailAddress, string phoneNumber, DataModels.Member.Member owner)
        {
            try
            {
                var dc = new ManagementContext();

                var email = new DataModels.ContactCard.Email();
                email.EmailAddress = emailAddress;
                email.IsDefault = true;

                var communication = new DataModels.ContactCard.Communication();
                communication.Data = phoneNumber;
                communication.IsDefault = true;
                int phoneNumberCast = Convert.ToInt32(CommunicationTypeEnum.PhoneNumber);
                //communication.CommunicationType = dc.CommunicationType.Where(x => x.CommunicationTypeId == phoneNumberCast).FirstOrDefault();
                communication.CommunicationTypeEnum = (byte)CommunicationTypeEnum.PhoneNumber;

                var card = new DataModels.ContactCard.ContactCard();
                card.Emails.Add(email);
                card.Communications.Add(communication);

                var fedOwner = new DataModels.Federation.FederationOwnership();
                fedOwner.IsVerified = false;
                var mem = dc.Members.Where(x => x.MemberId == owner.MemberId).FirstOrDefault();
                fedOwner.Member = mem;
                fedOwner.OwnerType = Convert.ToInt32(FederationOwnerEnum.Owner);

                var federation = new DataModels.Federation.Federation();
                federation.Name = nameOfFederation;
                federation.ContactCard = card;
                federation.IsVerified = false;
                federation.Owners.Add(fedOwner);

                //adds the current member to the federation they are creating.
                var fedMembers = new DataModels.Federation.FederationMember
                {
                    Federation = federation,
                    Member = mem,
                    FederationIdForMember = ""
                };

                federation.Members.Add(fedMembers);

                dc.Federations.Add(federation);
                dc.SaveChanges();

                Forum.Forum.CreateNewForum(federation.FederationId, ForumOwnerTypeEnum.league, nameOfFederation + "'s Forum");

                SendEmailAboutNewFederation(nameOfFederation, federation.FederationId, owner.DerbyName, emailAddress, phoneNumber);
                return federation;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: "Fed Name: " + nameOfFederation + " email:" + emailAddress + " phone:" + phoneNumber + " owner:" + owner.MemberId);
            }
            return null;
        }
        /// <summary>
        /// approves the league for federation purposes.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool ApproveLeagueForFederation(string id)
        {
            Guid leagueId;
            var guidConversion = Guid.TryParse(id, out leagueId);
            if (!guidConversion)
                return false;

            var dc = new ManagementContext();
            var pendingLeague = dc.LeaguePendings.Include("Creator").Include("Federation").Include("Country").FirstOrDefault(x => x.LeagueId.Equals(leagueId));
            if (pendingLeague == null)
                return false;

            var contactCard = new DataModels.ContactCard.ContactCard();
            var add = new Address
                                          {
                                              Country = pendingLeague.Country,
                                              StateRaw = pendingLeague.StateRaw,
                                              CityRaw = pendingLeague.CityRaw,
                                              TimeZone = pendingLeague.TimeZone
                                          };

            var coords = OpenStreetMap.FindLatLongOfAddress(string.Empty, string.Empty, string.Empty, add.CityRaw, add.StateRaw, add.Country != null ? add.Country.Name : string.Empty);
            if (coords != null)
            {
                add.Coords = new System.Device.Location.GeoCoordinate();
                add.Coords.Latitude = coords.Latitude;
                add.Coords.Longitude = coords.Longitude;
                add.Coords.Altitude = 0;
                add.Coords.Course = 0;
                add.Coords.HorizontalAccuracy = 1;
                add.Coords.Speed = 0;
                add.Coords.VerticalAccuracy = 1;
            }
            contactCard.Addresses.Add(add);

            contactCard.Emails.Add(new RDN.Library.DataModels.ContactCard.Email
            {
                EmailAddress = pendingLeague.ContactEmail,
                IsDefault = true
            });


            if (!String.IsNullOrEmpty(pendingLeague.ContactTelephone))
            {
                var communication = new DataModels.ContactCard.Communication();
                communication.Data = pendingLeague.ContactTelephone;
                communication.IsDefault = true;
                //int comType = Convert.ToInt32(CommunicationTypeEnum.PhoneNumber);
                //communication.CommunicationType = dc.CommunicationType.Where(x => x.CommunicationTypeId == comType).FirstOrDefault();
                communication.CommunicationTypeEnum = (byte)CommunicationTypeEnum.PhoneNumber;
                contactCard.Communications.Add(communication);
            }

            var league = new DataModels.League.League
                             {
                                 ContactCard = contactCard,
                                 Name = pendingLeague.LeagueName,
                                 LoweredName = pendingLeague.LeagueName.ToLower(),
                                 SubscriptionPeriodEnds = DateTime.UtcNow.AddDays(InvoiceSubscription.NUMBER_OF_DAYS_FOR_TRIAL_SUBSCRIPTION),
                                 SubscriptionWillAutoRenew = false
                             };

            if (pendingLeague.Federation != null)
            {
                FederationLeague l = new FederationLeague();
                l.League = league;
                l.Federation = pendingLeague.Federation;
                l.MembershipDate = DateTime.UtcNow;
                league.Federations.Add(l);
            }
            //league.Members.Add(pendingLeague.Creator);
            dc.Leagues.Add(league);
            var result = dc.SaveChanges();

            if (result == 0)
                return false;

            var membership = Membership.Providers["LeagueManagement"];
            var roles = Roles.Providers["LeagueManagement"];
            var user = membership.GetUser(pendingLeague.Creator.MemberId, false);
            //roles.AddUsersToRoles(new[] { user.UserName }, new[] { "League_President", "League_Member" });

            var defaultEmail = pendingLeague.Creator.ContactCard.Emails.FirstOrDefault(x => x.IsDefault.Equals(true));
            if (defaultEmail != null)
            {
                var emailData = new Dictionary<string, string>();
                emailData.Add("name", pendingLeague.Creator.Firstname);
                emailData.Add("derbyname", pendingLeague.Creator.DerbyName);
                emailData.Add("leaguename", pendingLeague.LeagueName);
                EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, defaultEmail.EmailAddress, EmailServer.EmailServer.DEFAULT_SUBJECT + " Your league has been approved", emailData, EmailServer.EmailServerLayoutsEnum.LeagueApproved);
            }

            // ToDo: To be removed
            //            var message = string.Format(@"
            //                                Hello {0} {1},
            //                                The league '{2}' has now been created. You can now login and administer the league.
            //                            ", pendingLeague.Creator.Firstname, pendingLeague.Creator.DerbyName, pendingLeague.LeagueName);


            //            SendEmail(, "ContactLeague creation successful", message);

            dc.LeaguePendings.Remove(pendingLeague);
            result = dc.SaveChanges();
            return result != 0;
        }
        public static Guid CreateLeagueForImport(string leagueName, string country, string state, string city, double timeZone, string email, string telephoneNumber, Guid federationId)
        {
            int result = 0;
            try
            {
                var dc = new ManagementContext();
                var count = dc.Countries.Where(x => x.CountryId == 0).FirstOrDefault();

                var contactCard = new DataModels.ContactCard.ContactCard();
                var add = new Address
                  {
                      Country = count,
                      StateRaw = state,
                      CityRaw = city,
                      TimeZone = timeZone
                  };
                var coords = OpenStreetMap.FindLatLongOfAddress(add.Address1, add.Address2, add.Zip, add.CityRaw, add.StateRaw, add.Country != null ? add.Country.Name : string.Empty);
                if (coords != null)
                {
                    add.Coords = new System.Device.Location.GeoCoordinate();
                    add.Coords.Latitude = coords.Latitude;
                    add.Coords.Longitude = coords.Longitude;
                    add.Coords.Altitude = 0;
                    add.Coords.Course = 0;
                    add.Coords.HorizontalAccuracy = 1;
                    add.Coords.Speed = 0;
                    add.Coords.VerticalAccuracy = 1;
                }
                contactCard.Addresses.Add(add);


                contactCard.Emails.Add(new RDN.Library.DataModels.ContactCard.Email
                {
                    EmailAddress = email,
                    IsDefault = true
                });


                if (!String.IsNullOrEmpty(telephoneNumber))
                {
                    var communication = new DataModels.ContactCard.Communication();
                    communication.Data = telephoneNumber;
                    communication.IsDefault = true;
                    int comType = Convert.ToInt32(CommunicationTypeEnum.PhoneNumber);
                    communication.CommunicationTypeEnum = (byte)CommunicationTypeEnum.PhoneNumber;
                    contactCard.Communications.Add(communication);
                }

                var league = new DataModels.League.League
                {
                    ContactCard = contactCard,
                    Name = leagueName,
                    LoweredName = leagueName.ToLower()
                };

                //we clear it by hitting a URL setup to clear the cache.
                var fed = dc.Federations.Where(x => x.FederationId == federationId).FirstOrDefault();

                FederationLeague fl = new FederationLeague();
                fl.League = league;
                fl.Federation = fed;
                fed.Leagues.Add(fl);

                //league.Members.Add(pendingLeague.Creator);
                dc.Leagues.Add(league);
                result = dc.SaveChanges();
                //    var result = 1;

                return league.LeagueId;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return new Guid();
        }