// GET api/MFUser
        //
        // Return list of all users
        //
        public HttpResponseMessage Get()
        {
            Repository    repository = new Repository();
            List <MFUser> users      = repository.GetAllUsers(GroupId);

            return(Request.CreateResponse(HttpStatusCode.OK, JsonUser.FromDatabase(users)));
        }
        // PUT api/<controller>
        //
        // Update user in the database
        //
        public HttpResponseMessage Put(string id, [FromBody] JsonUser value)
        {
            // Make sure the request is valid
            //
            if (string.IsNullOrEmpty(UserId))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized"));
            }

            Repository repository = new Repository();
            var        mfUser     = repository.GetUserByEmail(id);

            if (mfUser == null)
            {
                mfUser = repository.GetUserById(id);
            }

            if (mfUser == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found"));
            }

            if (String.Compare(mfUser.Email, value.Email, true) != 0)
            {
                var dup = repository.GetUserByEmail(value.Email);
                if (dup != null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Conflict, "Email already in use"));
                }
            }

            // Update the user properties (password, names)
            //
            mfUser.Email     = (!string.IsNullOrEmpty(value.Email) ? value.Email : mfUser.Email);
            mfUser.FirstName = (!string.IsNullOrEmpty(value.FirstName) ? value.FirstName : mfUser.FirstName);
            mfUser.LastName  = (!string.IsNullOrEmpty(value.LastName) ? value.LastName : mfUser.LastName);
            mfUser.Name      = (!string.IsNullOrEmpty(value.Name) ? value.Name : mfUser.Name);
            mfUser.Password  = (!string.IsNullOrEmpty(value.Password) ? value.Password : mfUser.Password);
            mfUser.UserId    = (!string.IsNullOrEmpty(value.UserId) ? value.UserId : mfUser.UserId);

            repository.SaveChanges();

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        public HttpResponseMessage Get(string id)
        {
            // Make sure the request is valid
            //
            if (string.IsNullOrEmpty(UserId))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized"));
            }

            Repository repository = new Repository();
            var        mfUser     = repository.GetUserByEmail(id);

            if (mfUser == null)
            {
                mfUser = repository.GetUserById(id);
            }

            if (mfUser == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found"));
            }

            return(Request.CreateResponse(HttpStatusCode.OK, JsonUser.FromDatabase(mfUser)));
        }
        // POST api/<controller>
        //
        // Create a new event.  Json eventInfo is passed in through the body of the POST
        //
        public HttpResponseMessage Post([FromBody] JsonEvent eventInfo)
        {
            // Make sure the request is valid
            //
            if (string.IsNullOrEmpty(UserId))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized"));
            }

            if (eventInfo == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Invalid Event Information"));
            }

            // Create new Model Event
            //
            RaceDayAPI.Models.Event iEvent = eventInfo.ToDatabase();
            iEvent.GroupId   = GroupId;
            iEvent.CreatorId = UserId;

            // Add to the database and then add this user as a participant
            //
            Repository repository = new Repository();
            Event      newEvent   = repository.AddEvent(iEvent);

            repository.SaveChanges();

            if ((newEvent != null) && (newEvent.EventId > 0))
            {
                var user = repository.GetUserById(UserId);
                repository.AddUserToEvent(user, newEvent, AttendingEnum.Attending);
                repository.SaveChanges();

                var addedEvent     = repository.GetEventViewById(newEvent.EventId, UserId);
                var eventAttendees = repository.GetUsersForEvent(newEvent.EventId);

                // Send an email notification
                //
                var smtp    = new SmtpClient();         // Settings in config file
                var message = new MailMessage("*****@*****.**", ConfigurationManager.AppSettings["AdminEmail"]);
                message.Subject    = "JYMF RaceDay New Event";
                message.IsBodyHtml = true;
                message.Body       = File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Data/NewEvent.txt"));
                message.Body       = message.Body.Replace("@NAME@", newEvent.Name)
                                     .Replace("@DATE@", newEvent.Date.ToShortDateString())
                                     .Replace("@URL@", newEvent.Url)
                                     .Replace("@LOCATION@", newEvent.Location)
                                     .Replace("@DESCRIPTION@", newEvent.Description)
                                     .Replace("@MFUSER@", this.UserId);

                smtp.Send(message);
                return(Request.CreateResponse(HttpStatusCode.Created, new { eventinfo = addedEvent, attendees = JsonUser.FromDatabase(eventAttendees) }));
            }

            return(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Unable to create event"));
        }
        // GET api/<controller>/5
        //
        // Return detailed event information along with all users attending the event
        //
        public HttpResponseMessage Get(int id)
        {
            if (string.IsNullOrEmpty(UserId))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized"));
            }

            Repository repository = new Repository();
            var        eventInfo  = repository.GetEventViewById(id, UserId);

            if (eventInfo != null)
            {
                var eventAttendees = repository.GetUsersForEvent(eventInfo.EventId);
                return(Request.CreateResponse(HttpStatusCode.OK, new { eventinfo = eventInfo, attendees = JsonUser.FromDatabase(eventAttendees) }));
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("Event {0} not found", id)));
            }
        }
        // POST api/<controller>
        //
        // Add user to the database
        //
        public HttpResponseMessage Post([FromBody] JsonUser value)
        {
            if (value == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid user information"));
            }

            Models.Repository repository = new Models.Repository();
            var user = repository.GetUserByEmail(value.Email);

            if (user != null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Conflict, "User with same email already exists"));
            }

            string groupCode = HttpContext.Current.Request.QueryString["code"];

            Models.Group defaultGroup = repository.FindGroupByCode((string.IsNullOrEmpty(groupCode) ? "JYMF" : groupCode));
            if (defaultGroup == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Group code not found"));
            }

            string userid;

            do
            {
                Random random = new Random();
                userid = (!string.IsNullOrEmpty(value.UserId) ? value.UserId : System.Web.Security.Membership.GeneratePassword(16, 0));
                userid = Regex.Replace(userid, @"[^a-zA-Z0-9]", m => random.Next(0, 9).ToString());

                user = repository.GetUserById(userid);
            } while (user != null);

            MFUser fbUser = new MFUser
            {
                UserId    = userid,
                Email     = value.Email,
                Password  = value.Password,
                FirstName = value.FirstName,
                LastName  = value.LastName,
                Name      = value.Name
            };
            var mfUser = repository.CreateUser(fbUser);

            repository.SaveChanges();

            if (repository.IsUserInGroup(mfUser, defaultGroup) == GroupRoleEnum.empty)
            {
                repository.DefaultGroup(mfUser, defaultGroup, GroupRoleEnum.member);
                repository.SaveChanges();
            }

            // Send an email notification
            //
            var smtp    = new SmtpClient();         // Settings in config file
            var message = new MailMessage("*****@*****.**", ConfigurationManager.AppSettings["AdminEmail"]);

            message.Subject    = "JYMF RaceDay New User";
            message.IsBodyHtml = true;
            message.Priority   = MailPriority.High;
            message.Body       = File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Data/NewUser.txt"));
            message.Body       = message.Body.Replace("@FIRSTNAME@", fbUser.FirstName)
                                 .Replace("@LASTNAME@", fbUser.LastName)
                                 .Replace("@EMAIL@", fbUser.Email);

            smtp.Send(message);

            return(Request.CreateResponse(HttpStatusCode.Created, "User added to application"));
        }