public HttpResponseMessage Clear(string id)
        {
            try
            {
                var respList = new List <string>();


                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                var notification = _context.Notifications.SingleOrDefault(x => x.Id == id);
                if (notification == null)
                {
                    respList.Add(id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_NOTIFICATION_NOTFOUND, respList)));
                }

                if (notification.UserId != account.UserId)
                {
                    respList.Add(notification.UserId);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_NOTIFICATION_WRONG_USER, respList)));
                }

                notification.Readed = true;
                _context.MarkAsModified(notification);
                _context.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_UPDATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage IsFavorite(string cardId)
        {
            var  currentUser = User as ServiceUser;
            var  account     = AuthUtils.GetUserAccount(_context, currentUser);
            bool status;

            if (account == null)
            {
                status = false;
            }
            else
            {
                status = _context.Favorites.AsNoTracking().Any(f => f.CardId == cardId && f.UserId == account.UserId);
            }
            return(Request.CreateResponse(HttpStatusCode.OK, RespH.CreateBool(RespH.SRV_DONE, new List <bool> {
                status
            })));
        }
        public HttpResponseMessage ClearAll()
        {
            try
            {
                var respList = new List <string>();

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                var notifications = _context.Notifications.Where(x => x.UserId == account.UserId && x.Readed == false);

                foreach (var notification in notifications)
                {
                    notification.Readed = true;
                    _context.MarkAsModified(notification);
                }

                _context.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_UPDATED)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage PutApartment(string id, ApartmentDTO apartment)
        {
            try
            {
                var         respList = new List <string>();
                ResponseDTO resp;
                // Check Apartment is not NULL
                if (apartment == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_APARTMENT_NULL)));
                }

                // Check Current Apartment is not NULL
                var apartmentCurrent = _context.Apartments.SingleOrDefault(a => a.Id == id);
                if (apartmentCurrent == null)
                {
                    respList.Add(id);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_APARTMENT_NOTFOUND, respList)));
                }

                // Check Apartment Name is not NULL
                resp = CheckHelper.IsNull(apartment.Name, "Name", RespH.SRV_APARTMENT_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                // Check Apartment Adress is not NULL
                resp = CheckHelper.IsNull(apartment.Adress, "Adress", RespH.SRV_APARTMENT_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }


                // Check Apartment Type is not NULL
                resp = CheckHelper.IsNull(apartment.Type, "Type", RespH.SRV_APARTMENT_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }


                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                // Check Apartment User
                if (apartment.UserId != account.UserId)
                {
                    respList.Add(apartment.UserId);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_APARTMENT_WRONG_USER, respList)));
                }
                if (apartmentCurrent.UserId != account.UserId)
                {
                    respList.Add(apartmentCurrent.UserId);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_APARTMENT_WRONG_USER, respList)));
                }

                // Update Apartment
                apartmentCurrent.Name      = apartment.Name;
                apartmentCurrent.Adress    = apartment.Adress;
                apartmentCurrent.Type      = apartment.Type;
                apartmentCurrent.Options   = apartment.Options;
                apartmentCurrent.Latitude  = apartment.Latitude;
                apartmentCurrent.Longitude = apartment.Longitude;
                apartmentCurrent.Lang      = apartment.Lang;
                _context.MarkAsModified(apartmentCurrent);
                _context.SaveChanges();

                respList.Add(apartment.Id);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_UPDATED, respList)));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.InnerException);
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage GetNotifications()
        {
            try
            {
                var respList = new List <string>();
                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                var notifications =
                    _context.Notifications.AsNoTracking().Where(n => n.UserId == account.UserId && n.Readed == false);
                var result = new List <NotificationDTO>();
                foreach (var notification in notifications)
                {
                    var notif = new NotificationDTO();
                    notif.Id        = notification.Id;
                    notif.Type      = notification.Type;
                    notif.UserId    = notification.UserId;
                    notif.Code      = notification.Code;
                    notif.Readed    = notification.Readed;
                    notif.CreatedAt = notification.CreatedAt;
                    notif.Data      = new NotificationData();

                    switch (notification.Code)
                    {
                    case RespH.SRV_NOTIF_RESERV_PENDING:
                        notif.Data.CardId           = notification.Reservation.CardId;
                        notif.Data.CardName         = notification.Reservation.Card.Name;
                        notif.Data.ReservationId    = notification.ReservationId;
                        notif.Data.ResrvationStatus = notification.Reservation.Status;
                        notif.Data.UserId           = notification.Reservation.UserId;
                        notif.Data.FirstName        = notification.Reservation.User.Profile.FirstName;
                        notif.Data.LastName         = notification.Reservation.User.Profile.LastName;
                        break;

                    case RespH.SRV_NOTIF_RESERV_ACCEPTED:
                        notif.Data.CardId           = notification.Reservation.CardId;
                        notif.Data.CardName         = notification.Reservation.Card.Name;
                        notif.Data.ReservationId    = notification.ReservationId;
                        notif.Data.ResrvationStatus = notification.Reservation.Status;
                        notif.Data.UserId           = notification.Reservation.Card.UserId;
                        notif.Data.FirstName        = notification.Reservation.Card.User.Profile.FirstName;
                        notif.Data.LastName         = notification.Reservation.Card.User.Profile.LastName;
                        break;

                    case RespH.SRV_NOTIF_RESERV_DECLINED:
                        notif.Data.CardId           = notification.Reservation.CardId;
                        notif.Data.CardName         = notification.Reservation.Card.Name;
                        notif.Data.ReservationId    = notification.ReservationId;
                        notif.Data.ResrvationStatus = notification.Reservation.Status;
                        notif.Data.UserId           = notification.Reservation.Card.UserId;
                        notif.Data.FirstName        = notification.Reservation.Card.User.Profile.FirstName;
                        notif.Data.LastName         = notification.Reservation.Card.User.Profile.LastName;
                        break;

                    case RespH.SRV_NOTIF_CARD_FAVORITED:
                        notif.Data.CardId    = notification.Favorite.CardId;
                        notif.Data.CardName  = notification.Favorite.Card.Name;
                        notif.Data.UserId    = notification.Favorite.UserId;
                        notif.Data.FirstName = notification.Favorite.User.Profile.FirstName;
                        notif.Data.LastName  = notification.Favorite.User.Profile.LastName;
                        break;

                    case RespH.SRV_NOTIF_REVIEW_ADDED:

                        notif.Data.ReviewId   = notification.ReviewId;
                        notif.Data.ReviewText = notification.Review.Text;
                        notif.Data.UserId     = notification.Review.FromUserId;
                        notif.Data.FirstName  = notification.Review.FromUser.Profile.FirstName;
                        notif.Data.LastName   = notification.Review.FromUser.Profile.LastName;
                        break;

                    case RespH.SRV_NOTIF_REVIEW_RATING_ADDED:

                        notif.Data.ReviewId     = notification.ReviewId;
                        notif.Data.ReviewText   = notification.Review.Text;
                        notif.Data.ReviewRating = notification.Review.Rating;
                        notif.Data.UserId       = notification.Review.FromUserId;
                        notif.Data.FirstName    = notification.Review.FromUser.Profile.FirstName;
                        notif.Data.LastName     = notification.Review.FromUser.Profile.LastName;
                        break;

                    case RespH.SRV_NOTIF_REVIEW_AVAILABLE:
                        notif.Data.CardId        = notification.Reservation.CardId;
                        notif.Data.CardName      = notification.Reservation.Card.Name;
                        notif.Data.ReservationId = notification.ReservationId;
                        break;
                    }
                    result.Add(notif);
                }
                return(Request.CreateResponse(HttpStatusCode.OK, result));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.ToString()
                })));
            }
        }
        public HttpResponseMessage GetReviews(string type = null)
        {
            var respList = new List <string>();

            // Check Current User
            var currentUser = User as ServiceUser;

            if (currentUser == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
            }
            var account = AuthUtils.GetUserAccount(_context, currentUser);

            if (account == null)
            {
                respList.Add(currentUser.Id);
                return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                              RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
            }

            var ownerReviews  = new List <ReservReviewDTO>();
            var renterReviews = new List <ReservReviewDTO>();
            var result        = new List <ReservReviewDTO>();

            if (type == ConstVals.Owner || string.IsNullOrWhiteSpace(type))
            {
                ownerReviews =
                    _context.Reservations.AsNoTracking().Where(
                        r => r.Card.UserId == account.UserId &&
                        r.Status == ConstVals.Accepted
                        ).OrderByDescending(r => r.CreatedAt)
                    .Select(
                        x => new ReservReviewDTO
                {
                    Reservation = new ReservationDTO
                    {
                        Id        = x.Id,
                        CardId    = x.CardId,
                        UserId    = x.UserId,
                        Status    = x.Status,
                        Gender    = x.Gender,
                        DateFrom  = x.DateFrom,
                        DateTo    = x.DateTo,
                        CreatedAt = x.CreatedAt,
                        UpdatedAt = x.UpdatedAt
                    }
                }).ToList();

                if (ownerReviews.Any())
                {
                    foreach (var owrev in ownerReviews)
                    {
                        owrev.Type             = ConstVals.Owner;
                        owrev.CanResponse      = owrev.Reservation.DateTo <= DateTime.Now;
                        owrev.Reservation.User =
                            _context.Users.AsNoTracking()
                            .Where(u => u.Id == owrev.Reservation.UserId)
                            .Select(x => new BaseUserDTO
                        {
                            Id          = x.Profile.Id,
                            Email       = x.Email,
                            FirstName   = x.Profile.FirstName,
                            LastName    = x.Profile.LastName,
                            Rating      = x.Profile.Rating,
                            RatingCount = x.Profile.RatingCount,
                            Gender      = x.Profile.Gender,
                            Picture     = new PictureDTO
                            {
                                //  Id = x.Profile.Picture.Id,
                                //  Name = x.Profile.Picture.Name,
                                //  Description = x.Profile.Picture.Description,
                                Url     = x.Profile.Picture.Url,
                                Xsmall  = x.Profile.Picture.Xsmall,
                                Small   = x.Profile.Picture.Small,
                                Mid     = x.Profile.Picture.Mid,
                                Large   = x.Profile.Picture.Large,
                                Xlarge  = x.Profile.Picture.Xlarge,
                                Default = x.Profile.Picture.Default
                                          //  CreatedAt = x.Profile.Picture.CreatedAt
                            }
                        }).FirstOrDefault();

                        owrev.OwnerReview =
                            _context.Reviews.AsNoTracking().Where(
                                rev => rev.ReservationId == owrev.Reservation.Id && rev.FromUserId == account.UserId)
                            .OrderByDescending(r => r.CreatedAt)
                            .Select(owreview => new ReviewDTO
                        {
                            Id            = owreview.Id,
                            FromUserId    = owreview.FromUserId,
                            ToUserId      = owreview.ToUserId,
                            ReservationId = owreview.ReservationId,
                            Rating        = owreview.Rating,
                            Text          = owreview.Text,
                            CreatedAt     = owreview.CreatedAt,
                            UpdatedAt     = owreview.UpdatedAt
                        }).FirstOrDefault();

                        owrev.RenterReview =
                            _context.Reviews.AsNoTracking()
                            .Where(
                                rev => rev.ReservationId == owrev.Reservation.Id && rev.ToUserId == account.UserId)
                            .OrderByDescending(r => r.CreatedAt)
                            .Select(renrev => new ReviewDTO
                        {
                            Id            = renrev.Id,
                            FromUserId    = renrev.FromUserId,
                            ToUserId      = renrev.ToUserId,
                            ReservationId = renrev.ReservationId,
                            Rating        = renrev.Rating,
                            Text          = renrev.Text,
                            CreatedAt     = renrev.CreatedAt,
                            UpdatedAt     = renrev.UpdatedAt
                        }).FirstOrDefault();
                        result.Add(owrev);
                    }
                }
            }
            if (type == ConstVals.Renter || string.IsNullOrWhiteSpace(type))
            {
                renterReviews =
                    _context.Reservations.AsNoTracking()
                    .Where(r => r.UserId == account.UserId && r.Status == ConstVals.Accepted)
                    .OrderByDescending(r => r.CreatedAt)
                    .Select(
                        x => new ReservReviewDTO
                {
                    Reservation = new ReservationDTO
                    {
                        Id        = x.Id,
                        CardId    = x.CardId,
                        UserId    = x.UserId,
                        Status    = x.Status,
                        Gender    = x.Gender,
                        DateFrom  = x.DateFrom,
                        DateTo    = x.DateTo,
                        CreatedAt = x.CreatedAt,
                        UpdatedAt = x.UpdatedAt
                    }
                }).ToList();

                if (renterReviews.Any())
                {
                    foreach (var rerev in renterReviews)
                    {
                        rerev.Type             = ConstVals.Renter;
                        rerev.CanResponse      = rerev.Reservation.DateTo <= DateTime.Now;
                        rerev.Reservation.Card =
                            _context.Cards.AsNoTracking().Where(c => c.Id == rerev.Reservation.CardId).Select(x =>
                                                                                                              new CardDTO
                        {
                            Id           = x.Id,
                            Name         = x.Name,
                            UserId       = x.UserId,
                            PriceDay     = x.Genders.FirstOrDefault(ge => ge.Name == rerev.Reservation.Gender).Price,
                            Cohabitation = x.Cohabitation,
                            IsFavorite   = x.Favorites.Any(f => f.UserId == account.UserId),
                            Apartment    = new ApartmentDTO
                            {
                                Id              = x.Apartment.Id,
                                Name            = x.Apartment.Name,
                                Type            = x.Apartment.Type,
                                Options         = x.Apartment.Options,
                                Adress          = x.Apartment.Adress,
                                FormattedAdress = x.Apartment.FormattedAdress,
                                Latitude        = x.Apartment.Latitude,
                                Longitude       = x.Apartment.Longitude,
                                PlaceId         = x.Apartment.PlaceId,
                                DefaultPicture  =
                                    x.Apartment.Pictures.Where(ap => ap.Default)
                                    .Select(apic => new PictureDTO
                                {
                                    //  Id = apic.Id,
                                    //  Name = apic.Name,
                                    //  Description = apic.Description,
                                    Url     = apic.Url,
                                    Xsmall  = apic.Xsmall,
                                    Small   = apic.Small,
                                    Mid     = apic.Mid,
                                    Large   = apic.Large,
                                    Xlarge  = apic.Xlarge,
                                    Default = apic.Default
                                              //  CreatedAt = apic.CreatedAt
                                }).FirstOrDefault()
                            },
                            User = new UserDTO
                            {
                                Id          = x.User.Id,
                                Email       = x.User.Email,
                                FirstName   = x.User.Profile.FirstName,
                                LastName    = x.User.Profile.LastName,
                                Rating      = x.User.Profile.Rating,
                                RatingCount = x.User.Profile.RatingCount,
                                Gender      = x.User.Profile.Gender,
                                Picture     = new PictureDTO
                                {
                                    //  Id = x.User.Profile.Picture.Id,
                                    //  Name = x.User.Profile.Picture.Name,
                                    //  Description = x.User.Profile.Picture.Description,
                                    Url     = x.User.Profile.Picture.Url,
                                    Xsmall  = x.User.Profile.Picture.Xsmall,
                                    Small   = x.User.Profile.Picture.Small,
                                    Mid     = x.User.Profile.Picture.Mid,
                                    Large   = x.User.Profile.Picture.Large,
                                    Xlarge  = x.User.Profile.Picture.Xlarge,
                                    Default = x.User.Profile.Picture.Default
                                              //  CreatedAt = x.User.Profile.Picture.CreatedAt
                                }
                            }
                        }).FirstOrDefault();

                        rerev.OwnerReview =
                            _context.Reviews.AsNoTracking()
                            .Where(
                                rev => rev.ReservationId == rerev.Reservation.Id && rev.ToUserId == account.UserId)
                            .OrderByDescending(r => r.CreatedAt)
                            .Select(owrev => new ReviewDTO
                        {
                            Id            = owrev.Id,
                            FromUserId    = owrev.FromUserId,
                            ToUserId      = owrev.ToUserId,
                            ReservationId = owrev.ReservationId,
                            Rating        = owrev.Rating,
                            Text          = owrev.Text,
                            CreatedAt     = owrev.CreatedAt,
                            UpdatedAt     = owrev.UpdatedAt
                        }).FirstOrDefault();

                        rerev.RenterReview =
                            _context.Reviews.AsNoTracking()
                            .Where(
                                rev => rev.ReservationId == rerev.Reservation.Id && rev.FromUserId == account.UserId)
                            .OrderByDescending(r => r.CreatedAt)
                            .Select(renrev => new ReviewDTO
                        {
                            Id            = renrev.Id,
                            FromUserId    = renrev.FromUserId,
                            ToUserId      = renrev.ToUserId,
                            ReservationId = renrev.ReservationId,
                            Rating        = renrev.Rating,
                            Text          = renrev.Text,
                            CreatedAt     = renrev.CreatedAt,
                            UpdatedAt     = renrev.UpdatedAt
                        }).FirstOrDefault();

                        result.Add(rerev);
                    }
                }
            }

            return(Request.CreateResponse(HttpStatusCode.OK, result));
        }
        public HttpResponseMessage UploadProfile(string id, PictureDTO picture)
        {
            try
            {
                var         respList = new List <string>();
                ResponseDTO resp;

                // Check Picture is not NULL
                if (picture == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_PICTURE_NULL)));
                }

                // Check Picture name is not NULL
                resp = CheckHelper.IsNull(picture.Name, "Name", RespH.SRV_PICTURE_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                // Check Picture CloudinaryPublicId is not NULL
                resp = CheckHelper.IsNull(picture.CloudinaryPublicId, "CloudinaryPublicId", RespH.SRV_PICTURE_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                // Check Current Profile is not NULL
                var profile = _context.Profile.SingleOrDefault(a => a.Id == id);
                if (profile == null)
                {
                    respList.Add(id);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                // Check Profile User
                if (profile.Id != account.UserId)
                {
                    respList.Add(profile.Id);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_WRONG_USER, respList)));
                }

                var pictureGuid = SequentialGuid.NewGuid().ToString();
                profile.Picture = new Picture
                {
                    Id          = pictureGuid,
                    Name        = picture.Name,
                    Description = picture.Description,
                    Url         = CloudinaryHelper.Cloudinary.Api.UrlImgUp.BuildUrl(picture.Name),
                    Small       =
                        CloudinaryHelper.Cloudinary.Api.UrlImgUp.Transform(
                            new Transformation().Width(34).Height(34).Crop("thumb")).BuildUrl(picture.Name),
                    Mid =
                        CloudinaryHelper.Cloudinary.Api.UrlImgUp.Transform(
                            new Transformation().Width(62).Height(62).Crop("thumb")).BuildUrl(picture.Name),
                    Large =
                        CloudinaryHelper.Cloudinary.Api.UrlImgUp.Transform(
                            new Transformation().Width(76).Height(76).Crop("thumb")).BuildUrl(picture.Name),
                    Xlarge =
                        CloudinaryHelper.Cloudinary.Api.UrlImgUp.Transform(
                            new Transformation().Width(96).Height(96).Crop("thumb")).BuildUrl(picture.Name),
                    Default = true
                };

                _context.SaveChanges();

                respList.Add(pictureGuid);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_CREATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage UploadApartment(string id, List <PictureDTO> pictures)
        {
            try
            {
                var         respList = new List <string>();
                ResponseDTO resp;

                // Check Pictures is not NULL
                if (pictures == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_PICTURE_NULL)));
                }


                // Check Apartment is not NULL
                var apartment = _context.Apartments.SingleOrDefault(a => a.Id == id);
                if (apartment == null)
                {
                    respList.Add(id);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_APARTMENT_NOTFOUND, respList)));
                }
                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                // Check Apartemtn User
                if (apartment.UserId != account.UserId)
                {
                    respList.Add(apartment.UserId);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_APARTMENT_WRONG_USER, respList)));
                }

                foreach (var picture in pictures)
                {
                    // Check Picture name is not NULL
                    resp = CheckHelper.IsNull(picture.Name, "Name", RespH.SRV_PICTURE_REQUIRED);
                    if (resp != null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                    }

                    // Check Picture CloudinaryPublicId is not NULL
                    resp = CheckHelper.IsNull(picture.CloudinaryPublicId, "CloudinaryPublicId",
                                              RespH.SRV_PICTURE_REQUIRED);
                    if (resp != null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                    }
                }

                foreach (var picture in pictures)
                {
                    var pictureGuid = SequentialGuid.NewGuid().ToString();
                    var pic         = new Picture
                    {
                        Id          = pictureGuid,
                        Name        = picture.Name,
                        Description = picture.Description,
                        Url         = CloudinaryHelper.Cloudinary.Api.UrlImgUp.BuildUrl(picture.Name),
                        Xsmall      =
                            CloudinaryHelper.Cloudinary.Api.UrlImgUp.Transform(
                                new Transformation().Width(143).Crop("thumb")).BuildUrl(picture.Name),
                        Small =
                            CloudinaryHelper.Cloudinary.Api.UrlImgUp.Transform(
                                new Transformation().Width(190).Crop("thumb")).BuildUrl(picture.Name),
                        Mid =
                            CloudinaryHelper.Cloudinary.Api.UrlImgUp.Transform(
                                new Transformation().Height(225).Width(370).Crop("fill")).BuildUrl(picture.Name),
                        Large =
                            CloudinaryHelper.Cloudinary.Api.UrlImgUp.Transform(
                                new Transformation().Width(552).Crop("limit")).BuildUrl(picture.Name),
                        Xlarge =
                            CloudinaryHelper.Cloudinary.Api.UrlImgUp.Transform(
                                new Transformation().Width(1024).Crop("limit")).BuildUrl(picture.Name),
                        Default = picture.Default ?? false
                    };
                    _context.Pictures.Add(pic);

                    _context.SaveChanges();
                    apartment.Pictures.Add(pic);
                    _context.SaveChanges();
                    respList.Add(pictureGuid);
                }
                var defaultPic =
                    _context.Pictures.SingleOrDefault(x => x.Default && x.Apartments.Any(a => a.Id == apartment.Id));
                if (defaultPic == null)
                {
                    var pic = _context.Pictures.SingleOrDefault(x => x.Id == apartment.Pictures.First().Id);
                    pic.Default = true;
                    _context.SaveChanges();
                }
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_CREATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage AcceptDeclineReservation(string reservId, string status)
        {
            try
            {
                var respList = new List <string>();

                // Check status is not NULL
                if (status == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_RESERVATION_NULL)));
                }

                // Check Status
                if (status != ConstVals.Accepted && status != ConstVals.Declined)
                {
                    respList.Add(status);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_WRONG_STATUS, respList)));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                ResponseDTO resp = CheckHelper.IsProfileFill(_context, account.UserId, true);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                //Check Reservation
                var currentReservation = _context.Reservations.SingleOrDefault(r => r.Id == reservId);
                // Check Reservation is not NULL
                if (currentReservation == null)
                {
                    respList.Add(reservId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_NOTFOUND, respList)));
                }

                var card =
                    _context.Cards.Include("Apartment")
                    .AsNoTracking()
                    .SingleOrDefault(a => a.Id == currentReservation.CardId);
                // Check CARD is not NULL
                if (card == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_CARD_NULL)));
                }


                // Check CARD User
                if (card.UserId != account.UserId)
                {
                    respList.Add(card.UserId);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_CARD_WRONG_USER, respList)));
                }


                string notifCode;
                //Check status
                if (status == ConstVals.Accepted)
                {
                    // Check Available Dates
                    var reservationDates = new TimeRange(currentReservation.DateFrom, currentReservation.DateTo);

                    var unavailableDates = new List <TimeRange>();

                    var cardDates = _context.Dates.Where(x => x.CardId == card.Id);
                    if (cardDates.Any())
                    {
                        foreach (var unDate in cardDates)
                        {
                            unavailableDates.Add(new TimeRange(unDate.DateFrom, unDate.DateTo));
                        }
                        if (unavailableDates.Any(unavailableDate => unavailableDate.IntersectsWith(reservationDates)))
                        {
                            respList.Add(reservationDates.ToString());
                            respList.Add(unavailableDates.ToString());
                            return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                          RespH.Create(RespH.SRV_RESERVATION_UNAVAILABLE_DATE, respList)));
                        }
                    }
                    var currentReservations =
                        _context.Reservations.AsNoTracking().Where(
                            r =>
                            r.CardId == currentReservation.CardId && currentReservation.Status == ConstVals.Accepted);
                    foreach (var currentReserv in currentReservations)
                    {
                        var reservedDates = new TimeRange(currentReserv.DateFrom, currentReserv.DateTo);
                        if (reservedDates.IntersectsWith(reservationDates))
                        {
                            respList.Add(reservationDates.ToString());
                            respList.Add(reservedDates.ToString());
                            return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                          RespH.Create(RespH.SRV_RESERVATION_UNAVAILABLE_DATE, respList)));
                        }
                    }
                    notifCode = RespH.SRV_NOTIF_RESERV_ACCEPTED;
                }
                else
                {
                    notifCode = RespH.SRV_NOTIF_RESERV_DECLINED;
                }

                currentReservation.Status = status;
                _context.MarkAsModified(currentReservation);
                _context.SaveChanges();
                // Create Notification
                Notifications.Create(_context, currentReservation.UserId, ConstVals.General, notifCode, null,
                                     currentReservation.Id, null);

                var fromUser    = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                var fromProfile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                var toUser      = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == currentReservation.UserId);
                var toProfile   = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == currentReservation.UserId);
                using (MailSender mailSender = new MailSender())
                {
                    var bem = new BaseEmailMessage
                    {
                        Code            = notifCode,
                        CardName        = card.Name,
                        CardType        = DicHelper.GetCardTypeByLang(card.Apartment.Type),
                        CardDescription = card.Description,
                        CardId          = card.Id,
                        DateFrom        = currentReservation.DateFrom,
                        DateTo          = currentReservation.DateTo,
                        FromUserName    = fromProfile.FirstName,
                        FromUserEmail   = fromUser.Email,
                        ToUserName      = toProfile.FirstName,
                        ToUserEmail     = toUser.Email,
                        UnsubscrCode    = toUser.EmailSubCode
                    };
                    mailSender.Create(_context, bem);
                }
                respList.Add(reservId);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_UPDATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage GetReservations(string type = null)
        {
            try
            {
                var respList = new List <string>();
                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                var ownerReserv  = new List <ReservationDTO>();
                var renterReserv = new List <ReservationDTO>();
                if (type == ConstVals.Owner || string.IsNullOrWhiteSpace(type))
                {
                    ownerReserv =
                        _context.Reservations.AsNoTracking().Where(x => x.Card.UserId == account.UserId)
                        .OrderByDescending(r => r.CreatedAt).Select(r => new ReservationDTO
                    {
                        Id        = r.Id,
                        Type      = ConstVals.Owner,
                        CardId    = r.CardId,
                        UserId    = r.UserId,
                        Status    = r.Status,
                        Gender    = r.Gender,
                        DateFrom  = r.DateFrom,
                        DateTo    = r.DateTo,
                        CreatedAt = r.CreatedAt,
                        UpdatedAt = r.UpdatedAt
                    }).ToList();
                }
                if (type == ConstVals.Renter || string.IsNullOrWhiteSpace(type))
                {
                    renterReserv =
                        _context.Reservations.AsNoTracking().Where(x => x.UserId == account.UserId)
                        .OrderByDescending(r => r.CreatedAt)
                        .Select(r => new ReservationDTO
                    {
                        Id        = r.Id,
                        Type      = ConstVals.Renter,
                        CardId    = r.CardId,
                        UserId    = r.UserId,
                        Status    = r.Status,
                        Gender    = r.Gender,
                        DateFrom  = r.DateFrom,
                        DateTo    = r.DateTo,
                        CreatedAt = r.CreatedAt,
                        UpdatedAt = r.UpdatedAt
                    }).ToList();
                }
                var resCount = ownerReserv.Count + renterReserv.Count;
                //if (resCount < 1)
                //{
                //    return Request.CreateResponse(HttpStatusCode.OK, new List<ReservationDTO>());
                //}
                var result       = new List <ReservationDTO>(resCount);
                var reservations = new List <ReservationDTO>(resCount);
                reservations.AddRange(ownerReserv);
                reservations.AddRange(renterReserv);


                if (!reservations.Any())
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, result));
                }
                foreach (var res in reservations)
                {
                    res.User =
                        _context.Users.AsNoTracking().Where(u => u.Id == res.UserId).Select(r => new BaseUserDTO
                    {
                        Id          = r.Profile.Id,
                        Email       = r.Email,
                        FirstName   = r.Profile.FirstName,
                        LastName    = r.Profile.LastName,
                        Rating      = r.Profile.Rating,
                        RatingCount = r.Profile.RatingCount,
                        Gender      = r.Profile.Gender,
                        Picture     = new PictureDTO
                        {
                            Id          = r.Profile.Picture.Id,
                            Name        = r.Profile.Picture.Name,
                            Description = r.Profile.Picture.Description,
                            Url         = r.Profile.Picture.Url,
                            Xsmall      = r.Profile.Picture.Xsmall,
                            Small       = r.Profile.Picture.Small,
                            Mid         = r.Profile.Picture.Mid,
                            Large       = r.Profile.Picture.Large,
                            Xlarge      = r.Profile.Picture.Xlarge,
                            Default     = r.Profile.Picture.Default,
                            CreatedAt   = r.Profile.Picture.CreatedAt
                        }
                    }).FirstOrDefault();

                    res.Card =
                        _context.Cards.AsNoTracking().Where(x => x.Id == res.CardId).Select(r => new CardDTO
                    {
                        Name         = r.Name,
                        UserId       = r.UserId,
                        Description  = r.Description,
                        ApartmentId  = r.ApartmentId,
                        PriceDay     = r.Genders.FirstOrDefault(ge => ge.Name == res.Gender).Price,
                        Cohabitation = r.Cohabitation,
                        Lang         = r.Lang,
                        Dates        = r.Dates.Select(d => new DatesDTO
                        {
                            DateFrom = d.DateFrom,
                            DateTo   = d.DateTo
                        })
                                       .Union(
                            r.Reservations.Where(reserv => reserv.Status == ConstVals.Accepted)
                            .Select(rv => new DatesDTO
                        {
                            DateFrom = rv.DateFrom,
                            DateTo   = rv.DateTo
                        }).ToList()).ToList(),
                        User = new UserDTO
                        {
                            Id          = r.User.Profile.Id,
                            FirstName   = r.User.Profile.FirstName,
                            LastName    = r.User.Profile.LastName,
                            Rating      = r.User.Profile.Rating,
                            RatingCount = r.User.Profile.RatingCount,
                            Gender      = r.User.Profile.Gender,
                            Phone       = r.User.Profile.Phone,
                            Picture     = new PictureDTO
                            {
                                Id          = r.User.Profile.Picture.Id,
                                Name        = r.User.Profile.Picture.Name,
                                Description = r.User.Profile.Picture.Description,
                                Url         = r.User.Profile.Picture.Url,
                                Xsmall      = r.User.Profile.Picture.Xsmall,
                                Small       = r.User.Profile.Picture.Small,
                                Mid         = r.User.Profile.Picture.Mid,
                                Large       = r.User.Profile.Picture.Large,
                                Xlarge      = r.User.Profile.Picture.Xlarge,
                                Default     = r.User.Profile.Picture.Default,
                                CreatedAt   = r.User.Profile.Picture.CreatedAt
                            }
                        },
                        Apartment = new ApartmentDTO
                        {
                            Id        = r.Apartment.Id,
                            Name      = r.Apartment.Name,
                            Type      = r.Apartment.Type,
                            Options   = r.Apartment.Options,
                            UserId    = r.Apartment.UserId,
                            Adress    = r.Apartment.Adress,
                            Latitude  = r.Apartment.Latitude,
                            Longitude = r.Apartment.Longitude
                        }
                    }).FirstOrDefault();
                    result.Add(res);
                }


                return(Request.CreateResponse(HttpStatusCode.OK, result));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.ToString()
                })));
            }
        }
        public HttpResponseMessage MakeReservation(string cardId, string gender, DateTime dateFrom, DateTime dateTo)
        {
            try
            {
                var respList = new List <string>();

                // Check Reservation is not NULL
                if (cardId == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_RESERVATION_NULL)));
                }

                var card = _context.Cards.Include("Apartment").SingleOrDefault(a => a.Id == cardId);
                // Check CARD is not NULL
                if (card == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_CARD_NULL)));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                // Check Card Owner
                if (card.UserId == account.UserId)
                {
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_SELF, respList)));
                }
                ResponseDTO resp = CheckHelper.IsProfileFill(_context, account.UserId);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }


                // Check CARD User
                //if (CARD.UserId != account.UserId)
                //{
                //    respList.Add(CARD.UserId);
                //    respList.Add(account.UserId);
                //    return this.Request.CreateResponse(HttpStatusCode.BadRequest,
                //        RespH.Create(RespH.SRV_CARD_WRONG_USER, respList));
                //}

                // Check Dates
                if (DateTime.Compare(dateFrom, dateTo) > 0)
                {
                    respList.Add(dateFrom.ToLocalTime().ToString(CultureInfo.InvariantCulture));
                    respList.Add(dateTo.ToLocalTime().ToString(CultureInfo.InvariantCulture));
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_CARD_WRONG_DATE, respList)));
                }

                // Check Reservation already exists
                if (
                    _context.Reservations.AsNoTracking().Any(
                        x =>
                        x.UserId == account.UserId && x.CardId == cardId && x.DateFrom == dateFrom &&
                        x.DateTo == dateTo))
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_EXISTS)));
                }

                // Check Available Dates
                var reservationDates = new TimeRange(dateFrom, dateTo);

                var unavailableDates =
                    _context.Dates.AsNoTracking().Where(x => x.CardId == card.Id)
                    .ToList()
                    .Select(unDate => new TimeRange(unDate.DateFrom, unDate.DateTo))
                    .ToList();

                if (unavailableDates.Any(unavailableDate => unavailableDate.IntersectsWith(reservationDates)))
                {
                    respList.Add(reservationDates.ToString());
                    respList.Add(unavailableDates.ToString());
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_UNAVAILABLE_DATE, respList)));
                }

                var currentReservations =
                    _context.Reservations.AsNoTracking()
                    .Where(r => r.CardId == cardId && r.Status == ConstVals.Accepted);
                foreach (var currentReservation in currentReservations)
                {
                    var reservedDates = new TimeRange(currentReservation.DateFrom, currentReservation.DateTo);
                    if (reservedDates.IntersectsWith(reservationDates))
                    {
                        respList.Add(reservationDates.ToString());
                        respList.Add(reservedDates.ToString());
                        return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                      RespH.Create(RespH.SRV_RESERVATION_UNAVAILABLE_DATE, respList)));
                    }
                }

                var reservationGuid = SequentialGuid.NewGuid().ToString();
                _context.Reservations.Add(new Reservation
                {
                    Id       = reservationGuid,
                    CardId   = cardId,
                    UserId   = account.UserId,
                    Status   = ConstVals.Pending,
                    Gender   = gender,
                    DateFrom = dateFrom,
                    DateTo   = dateTo
                });
                _context.SaveChanges();
                // Create Notification
                Notifications.Create(_context, card.UserId, ConstVals.General, RespH.SRV_NOTIF_RESERV_PENDING, null,
                                     reservationGuid, null);

                var user    = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                var profile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                if (user.EmailNotifications)
                {
                    using (MailSender mailSender = new MailSender())
                    {
                        var bem = new BaseEmailMessage
                        {
                            Code            = RespH.SRV_NOTIF_RESERV_PENDING,
                            CardName        = card.Name,
                            CardType        = DicHelper.GetCardTypeByLang(card.Apartment.Type),
                            CardDescription = card.Description,
                            DateFrom        = dateFrom,
                            DateTo          = dateTo,
                            ToUserName      = profile.FirstName,
                            ToUserEmail     = user.Email,
                            CardId          = card.Id,
                            UnsubscrCode    = user.EmailSubCode
                        };
                        mailSender.Create(_context, bem);
                    }
                }

                var cardUser    = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == card.UserId);
                var cardProfile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == card.UserId);
                if (cardUser.EmailNotifications)
                {
                    using (MailSender mailSender = new MailSender())
                    {
                        var bem = new BaseEmailMessage
                        {
                            Code            = RespH.SRV_NOTIF_RESERV_NEW,
                            CardName        = card.Name,
                            CardType        = DicHelper.GetCardTypeByLang(card.Apartment.Type),
                            CardDescription = card.Description,
                            FromUserName    = profile.FirstName,
                            DateFrom        = dateFrom,
                            DateTo          = dateTo,
                            ToUserName      = cardProfile.FirstName,
                            ToUserEmail     = cardUser.Email,
                            CardId          = card.Id,
                            UnsubscrCode    = cardUser.EmailSubCode
                        };
                        mailSender.Create(_context, bem);
                    }
                }
                respList.Add(reservationGuid);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_CREATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage SetEmail(UserDTO userdata)
        {
            try
            {
                var respList = new List <string>();

                if (string.IsNullOrWhiteSpace(userdata.Email))
                {
                    respList.Add("Email");
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_REQUIRED, respList)));
                }

                if (!AuthUtils.IsEmailValid(userdata.Email))
                {
                    respList.Add(userdata.Email);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_REG_INVALID_EMAIL, respList)));
                }
                var usersame = _context.Users.AsNoTracking().SingleOrDefault(a => a.Email == userdata.Email);
                if (usersame != null)
                {
                    respList.Add(userdata.Email);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_REG_EXISTS_EMAIL, respList)));
                }
                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                var user    = _context.Users.SingleOrDefault(x => x.Id == account.UserId);
                var profile = _context.Profile.SingleOrDefault(x => x.Id == account.UserId);
                if (user == null || profile == null)
                {
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                if (!string.IsNullOrWhiteSpace(user.Email))
                {
                    respList.Add(user.Email);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_EXISTS, respList)));
                }

                var salt        = AuthUtils.GenerateSalt();
                var confirmCode = AuthUtils.RandomNumString(6);
                user.Email = userdata.Email;
                user.Salt  = salt;
                user.SaltedAndHashedEmail = AuthUtils.Hash(confirmCode, salt);
                _context.MarkAsModified(user);
                _context.SaveChanges();
                using (MailSender mailSender = new MailSender())
                {
                    var bem = new BaseEmailMessage
                    {
                        Code        = ConstVals.Reg,
                        ToUserId    = user.Id,
                        ToUserEmail = user.Email,
                        ToUserName  = profile.FirstName,
                        ConfirmCode = confirmCode
                    };
                    mailSender.Create(_context, bem);
                }


                respList.Add(user.Id);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_UPDATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.ToString()
                })));
            }
        }
        public HttpResponseMessage PutCurrentUser(UserDTO profile)
        {
            try
            {
                var         respList = new List <string>();
                ResponseDTO resp;
                // Check Profile is not NULL
                if (profile == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_USER_NULL)));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                // Check Profile User
                if (profile.Id != account.UserId)
                {
                    respList.Add(profile.Id);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_WRONG_USER, respList)));
                }

                var user = _context.Users.AsNoTracking().SingleOrDefault(u => u.Id == account.UserId);
                if (user == null)
                {
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                // Check Current Profile is not NULL
                var profileCurrent = _context.Profile.SingleOrDefault(a => a.Id == account.UserId);
                if (profileCurrent == null)
                {
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                if (!string.IsNullOrWhiteSpace(profile.Phone))
                {
                    profile.Phone = CheckHelper.CleanPhone(profile.Phone);
                    if (profile.Phone[0] == '7')
                    {
                        if (profile.Phone.Length != 11)
                        {
                            respList.Add(profile.Phone);
                            return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                          RespH.Create(RespH.SRV_PROFILE_WRONG_PHONE, respList)));
                        }
                    }
                    if (profileCurrent.Phone != profile.Phone)
                    {
                        var hasCards = _context.Cards.Any(x => x.UserId == user.Id);
                        if (hasCards)
                        {
                            respList.Add(user.Id);
                            return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                          RespH.Create(RespH.SRV_PROFILE_ERR_UPDATE_PHONE, respList)));
                        }
                        user.PhoneStatus = ConstVals.PUnconf;
                        _context.MarkAsModified(user);
                    }
                }
                else
                {
                    var hasCards = _context.Cards.Any(x => x.UserId == user.Id);
                    if (hasCards)
                    {
                        respList.Add(user.Id);
                        return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                      RespH.Create(RespH.SRV_PROFILE_ERR_UPDATE_PHONE, respList)));
                    }
                    user.PhoneStatus = ConstVals.PUnconf;
                    _context.MarkAsModified(user);
                }
                // Check FirstName is not NULL
                resp = CheckHelper.IsNull(profile.FirstName, "FirstName", RespH.SRV_USER_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                // Check LastName is not NULL
                //resp = CheckHelper.IsNull(profile.LastName, "LastName", RespH.SRV_USER_REQUIRED);
                //if (resp != null) return Request.CreateResponse(HttpStatusCode.BadRequest, resp);

                // Check Phone is not NULL
                //resp = CheckHelper.IsNull(profile.Phone, "Phone", RespH.SRV_USER_REQUIRED);
                //if (resp != null) return Request.CreateResponse(HttpStatusCode.BadRequest, resp);

                // Check Genderis not NULL
                //resp = CheckHelper.IsNull(profile.Gender, "Gender", RespH.SRV_USER_REQUIRED);
                //if (resp != null) return Request.CreateResponse(HttpStatusCode.BadRequest, resp);

                profileCurrent.FirstName   = profile.FirstName;
                profileCurrent.LastName    = profile.LastName;
                profileCurrent.Gender      = profile.Gender;
                profileCurrent.Birthday    = profile.Birthday;
                profileCurrent.Phone       = profile.Phone;
                profileCurrent.Description = profile.Description;
                user.EmailNotifications    = profile.EmailNotifications;
                user.EmailNewsletter       = profile.EmailNewsletter;
                _context.MarkAsModified(user);
                _context.MarkAsModified(profileCurrent);
                _context.SaveChanges();

                respList.Add(profileCurrent.Id);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_UPDATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.ToString()
                })));
            }
        }
        public HttpResponseMessage PutReview(string revId, ReviewDTO review)
        {
            try
            {
                var         respList = new List <string>();
                ResponseDTO resp;

                // Check Review  exist
                var currentReview =
                    _context.Reviews.SingleOrDefault(
                        r => r.Id == revId);
                if (currentReview == null)
                {
                    respList.Add(revId);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_REVIEW_NOTFOUND, respList)));
                }

                // Check Reservation is not NULL
                var reservation =
                    _context.Reservations.AsNoTracking().SingleOrDefault(x => x.Id == currentReview.ReservationId);
                if (reservation == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_NOTFOUND)));
                }

                // Check Reservation Status is Accepted
                if (reservation.Status != ConstVals.Accepted)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_REVIEW_WRONG_RESERV_STATUS)));
                }

                // Check Reservation Dates
                if (reservation.DateTo >= DateTime.Now)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_REVIEW_WRONG_DATE)));
                }

                // Check Review Text is not NULL
                resp = CheckHelper.IsNull(review.Text, "Text", RespH.SRV_REVIEW_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                resp = CheckHelper.IsProfileFill(_context, account.UserId);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                // Check Review User
                if (currentReview.FromUserId != account.UserId)
                {
                    respList.Add(currentReview.FromUserId);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_REVIEW_WRONG_USER, respList)));
                }


                currentReview.Text = review.Text;
                _context.MarkAsModified(currentReview);
                _context.SaveChanges();
                respList.Add(currentReview.Id);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_UPDATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage DeleteApartment(string id)
        {
            try
            {
                var respList  = new List <string>();
                var apartment = _context.Apartments.SingleOrDefault(a => a.Id == id);

                // Check Apartment is not NULL
                if (apartment == null)
                {
                    respList.Add(id);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_APARTMENT_NOTFOUND, respList)));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                // Check Apartment User
                if (apartment.UserId != account.UserId)
                {
                    respList.Add(apartment.UserId);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_APARTMENT_WRONG_USER, respList)));
                }

                // Check Adverts with such Apartment
                var adverts = _context.Cards.Where(adv => adv.ApartmentId == id).Select(a => a.Id);
                if (adverts.Any())
                {
                    foreach (var advert in adverts)
                    {
                        respList.Add(advert);
                    }
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_APARTMENT_DEPENDENCY, respList)));
                }

                // Delete Apartment with PropVals
                _context.Apartments.Remove(apartment);
                _context.SaveChanges();
                respList.Add(apartment.Id);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_DELETED, respList)));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.InnerException);
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage PostApartment(ApartmentDTO apartment)
        {
            try
            {
                var         respList = new List <string>();
                ResponseDTO resp;
                // Check Apartment is not NULL
                if (apartment == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_APARTMENT_NULL)));
                }


                // Check Apartment Name is not NULL
                resp = CheckHelper.IsNull(apartment.Name, "Name", RespH.SRV_APARTMENT_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                // Check Apartment Adress is not NULL
                resp = CheckHelper.IsNull(apartment.Adress, "Adress", RespH.SRV_APARTMENT_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }


                // Check Apartment Type is not NULL
                resp = CheckHelper.IsNull(apartment.Type, "Type", RespH.SRV_APARTMENT_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                // Generate
                var apartmentGuid = SequentialGuid.NewGuid().ToString();
                _context.Apartments.Add(new Apartment
                {
                    Id        = apartmentGuid,
                    Name      = apartment.Name,
                    Type      = apartment.Type,
                    Options   = apartment.Options,
                    UserId    = account.UserId,
                    Adress    = apartment.Adress,
                    Latitude  = apartment.Latitude,
                    Longitude = apartment.Longitude,
                    Lang      = apartment.Lang
                });


                _context.SaveChanges();
                respList.Add(apartmentGuid);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_CREATED, respList)));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.InnerException);
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage ChangePassword(ConfirmRequest resetRequest)
        {
            try
            {
                User user;
                if (!string.IsNullOrEmpty(resetRequest.UserId) || !string.IsNullOrEmpty(resetRequest.Email))
                {
                    if (resetRequest.Code == null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                      RespH.Create(RespH.SRV_USER_REQUIRED, new List <string> {
                            "code"
                        })));
                    }

                    user = !string.IsNullOrEmpty(resetRequest.UserId)
                        ? _context.Users.SingleOrDefault(x => x.Id == resetRequest.UserId)
                        : _context.Users.SingleOrDefault(x => x.Email == resetRequest.Email);
                    if (user == null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                      RespH.Create(RespH.SRV_USER_NOTFOUND,
                                                                   new List <string> {
                            resetRequest.UserId ?? resetRequest.Email
                        })));
                    }


                    var standartAccount =
                        _context.Accounts.SingleOrDefault(
                            x => x.Provider == StandartLoginProvider.ProviderName && x.UserId == user.Id);
                    if (standartAccount == null)
                    {
                        var newstandartaccount = new Account
                        {
                            Id         = SequentialGuid.NewGuid().ToString(),
                            UserId     = user.Id,
                            AccountId  = StandartLoginProvider.ProviderName + ":" + user.Email,
                            Provider   = StandartLoginProvider.ProviderName,
                            ProviderId = user.Email
                        };
                        _context.Accounts.Add(newstandartaccount);
                        _context.SaveChanges();
                    }

                    if (!user.ResetRequested)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                      RespH.Create(RespH.SRV_USER_RESET_NOT_REQUESTED,
                                                                   new List <string> {
                            resetRequest.UserId ?? resetRequest.Email
                        })));
                    }
                    var incoming = AuthUtils.Hash(resetRequest.Code, user.Salt);

                    if (!AuthUtils.SlowEquals(incoming, user.SaltedAndHashedCode))
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                      RespH.Create(RespH.SRV_USER_WRONG_CODE,
                                                                   new List <string> {
                            resetRequest.UserId ?? resetRequest.Email, resetRequest.Code
                        })));
                    }

                    user.SaltedAndHashedCode = null;
                    user.EmailConfirmed      = true;
                    user.ResetRequested      = false;
                }
                else
                {
                    // Check Current User
                    var currentUser = User as ServiceUser;
                    if (currentUser == null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                    }
                    var account = AuthUtils.GetUserAccount(_context, currentUser);
                    if (account == null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                      RespH.Create(RespH.SRV_USER_NOTFOUND, new List <string> {
                            currentUser.Id
                        })));
                    }
                    user =
                        _context.Users.SingleOrDefault(x => x.Id == account.UserId);
                    if (user == null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                      RespH.Create(RespH.SRV_USER_NOTFOUND,
                                                                   new List <string> {
                            account.UserId
                        })));
                    }

                    var standartAccount =
                        _context.Accounts.SingleOrDefault(
                            x => x.Provider == StandartLoginProvider.ProviderName && x.UserId == user.Id);
                    if (standartAccount == null)
                    {
                        var newstandartaccount = new Account
                        {
                            Id         = SequentialGuid.NewGuid().ToString(),
                            UserId     = user.Id,
                            AccountId  = StandartLoginProvider.ProviderName + ":" + user.Email,
                            Provider   = StandartLoginProvider.ProviderName,
                            ProviderId = user.Email
                        };
                        _context.Accounts.Add(newstandartaccount);
                        _context.SaveChanges();
                    }
                    if (string.IsNullOrWhiteSpace(resetRequest.CurrentPassword))
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                      RespH.Create(RespH.SRV_USER_REQUIRED, new List <string> {
                            "current password"
                        })));
                    }

                    if (
                        !AuthUtils.SlowEquals(AuthUtils.Hash(resetRequest.CurrentPassword, user.Salt),
                                              user.SaltedAndHashedPassword))
                    {
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                      RespH.Create(RespH.SRV_LOGIN_INVALID_PASS)));
                    }
                }
                if (string.IsNullOrWhiteSpace(resetRequest.Password))
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_REQUIRED, new List <string> {
                        "password"
                    })));
                }
                if (resetRequest.Password.Length < 8)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_REG_INVALID_PASSWORD, new List <string> {
                        resetRequest.Password
                    })));
                }
                var salt = AuthUtils.GenerateSalt();
                user.Salt = salt;
                user.SaltedAndHashedPassword = AuthUtils.Hash(resetRequest.Password, salt);
                _context.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.OK,
                                              RespH.Create(RespH.SRV_USER_RESETED, new List <string> {
                    user.Id
                })));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.ToString()
                })));
            }
        }
        public HttpResponseMessage SetDefault(string id)
        {
            try
            {
                var respList = new List <string>();
                var pic      = _context.Pictures.SingleOrDefault(x => x.Id == id);
                if (pic == null)
                {
                    respList.Add(id);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_PICTURE_NOTFOUND, respList)));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                var pics =
                    _context.Pictures.Where(
                        x => x.Apartments.Any(a => a.UserId == account.UserId && a.Pictures.Any(p => p.Id == id)));
                if (pics.Any())
                {
                    foreach (var other in pics.Where(x => x.Id != id && x.Default))
                    {
                        other.Default = false;
                    }
                    pic.Default = true;
                }
                else
                {
                    if (_context.Profile.Any(x => x.Picture.Id == id && x.Id == account.UserId))
                    {
                        pic.Default = true;
                    }
                }
                if (pic.Default)
                {
                    _context.MarkAsModified(pic);
                    _context.SaveChanges();
                    return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_UPDATED)));
                }

                return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_USER_WRONG_USER)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.ToString()
                })));
            }
        }
예제 #19
0
        public HttpResponseMessage ConfirmCode(ConfirmRequest confirmRequest)
        {
            try
            {
                var respList = new List <string>();
                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                var user = _context.Users.SingleOrDefault(x => x.Id == account.UserId);
                if (user == null)
                {
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                if (user.PhoneStatus == ConstVals.PConf)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_PHONE_CONFIRMED, new List <string> {
                        user.Id
                    })));
                }
                if (confirmRequest.Code == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_REQUIRED, new List <string> {
                        "code"
                    })));
                }
                var incoming = AuthUtils.Hash(confirmRequest.Code, user.Salt);

                if (!AuthUtils.SlowEquals(incoming, user.SaltedAndHashedSmsCode))
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_WRONG_CODE,
                                                               new List <string> {
                        user.Id, confirmRequest.Code
                    })));
                }
                user.SaltedAndHashedSmsCode = null;
                user.PhoneStatus            = ConstVals.PConf;
                user.PhoneCodeRequestedAt   = null;
                _context.MarkAsModified(user);
                _context.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.OK,
                                              RespH.Create(RespH.SRV_USER_PHONE_CONFIRMED, new List <string> {
                    user.PhoneStatus
                })));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage DeleteApartment(string id, List <string> picIds)
        {
            try
            {
                var respList = new List <string>();
                // Check Current Profile is not NULL
                var apartment = _context.Apartments.SingleOrDefault(a => a.Id == id);
                if (apartment == null)
                {
                    respList.Add(id);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_APARTMENT_NOTFOUND, respList)));
                }
                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                // Check Apartemtn User
                if (apartment.UserId != account.UserId)
                {
                    respList.Add(apartment.UserId);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_APARTMENT_WRONG_USER, respList)));
                }
                string cloudname;
                string apikey;
                string apisecret;
                if (!(Services.Settings.TryGetValue("CLOUDINARY_CLOUD_NAME", out cloudname) |
                      Services.Settings.TryGetValue("CLOUDINARY_API_KEY", out apikey) |
                      Services.Settings.TryGetValue("CLOUDINARY_API_SECRET", out apisecret)))
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_PICTURE_BAD_CLOUDINARY_CRED)));
                }

                var clacc = new Account(
                    cloudname,
                    apikey,
                    apisecret);
                var cloudinary = new Cloudinary(clacc);
                foreach (var picId in picIds)
                {
                    var pic = _context.Pictures.SingleOrDefault(p => p.Id == picId);
                    if (pic != null)
                    {
                        cloudinary.DeleteResources(pic.CloudinaryPublicId);
                        apartment.Pictures.Remove(pic);
                        _context.SaveChanges();
                        _context.Pictures.Remove(pic);
                        _context.SaveChanges();
                    }
                }
                if (apartment.Pictures.Any())
                {
                    var defaultPic = apartment.Pictures.SingleOrDefault(x => x.Default);
                    if (defaultPic == null)
                    {
                        var pic = _context.Pictures.SingleOrDefault(x => x.Id == apartment.Pictures.First().Id);
                        pic.Default = true;
                        _context.SaveChanges();
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_DELETED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
예제 #21
0
        public HttpResponseMessage ReqeustCode()
        {
            try
            {
                var         respList = new List <string>();
                ResponseDTO resp;
                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                var user = _context.Users.SingleOrDefault(x => x.Id == account.UserId);
                if (user == null)
                {
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                var profile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);


                resp = CheckHelper.IsNull(profile.Phone, "Phone", RespH.SRV_USER_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                if (user.PhoneStatus == ConstVals.PConf)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_USER_PHONE_CONFIRMED, new List <string> {
                        user.PhoneStatus
                    })));
                }
                if (user.PhoneCodeRequestedAt.HasValue && user.PhoneStatus == ConstVals.PPending)
                {
                    if (user.PhoneCodeRequestedAt.Value.AddMinutes(3) > DateTime.Now)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                      RespH.Create(RespH.SRV_USER_PHONE_CONFIRM_REQUESTED,
                                                                   new List <string> {
                            user.PhoneCodeRequestedAt.ToString()
                        })));
                    }
                }
                var confirmCode = AuthUtils.RandomNumString(4);
                user.SaltedAndHashedSmsCode = AuthUtils.Hash(confirmCode, user.Salt);
                user.PhoneCodeRequestedAt   = DateTime.Now;
                user.PhoneStatus            = ConstVals.PPending;
                _context.MarkAsModified(user);
                _context.SaveChanges();

                var    regArt = _context.Article.SingleOrDefault(x => x.Name == ConstVals.Reg && x.Type == ConstVals.Sms);
                string smstext;
                if (regArt != null)
                {
                    smstext = confirmCode + " " + regArt.Text;
                }
                else
                {
                    smstext = confirmCode;
                }
                using (SmsSender sender = new SmsSender())
                {
                    sender.Send(profile.Phone, smstext);
                }
                return(Request.CreateResponse(HttpStatusCode.OK,
                                              RespH.Create(RespH.SRV_DONE, new List <string> {
                    user.PhoneStatus
                })));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage SetFavorite(string cardId)
        {
            try
            {
                var respList = new List <string>();

                // Check advertId is not NULL
                if (cardId == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_FAVORITE_CARDID_NULL)));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                var currentCard = _context.Cards.AsNoTracking().SingleOrDefault(a => a.Id == cardId);
                if (currentCard == null)
                {
                    respList.Add(cardId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_CARD_NOTFOUND, respList)));
                }

                if (currentCard.UserId == account.UserId)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.CreateBool(RespH.SRV_FAVORITE_WRONG_USER)));
                }
                bool status;
                var  favorite =
                    _context.Favorites.SingleOrDefault(f => f.CardId == cardId && f.UserId == account.UserId);
                if (favorite == null)
                {
                    var favoriteGUID = SequentialGuid.NewGuid().ToString();
                    _context.Favorites.Add(new Favorite
                    {
                        Id     = favoriteGUID,
                        CardId = cardId,
                        UserId = account.UserId
                    });
                    _context.SaveChanges();
                    // Create Notification
                    Notifications.Create(_context, currentCard.UserId, ConstVals.General, RespH.SRV_NOTIF_CARD_FAVORITED,
                                         favoriteGUID, null, null);

                    var user    = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                    var profile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                    if (user.EmailNotifications)
                    {
                        using (MailSender mailSender = new MailSender())
                        {
                            var bem = new BaseEmailMessage
                            {
                                Code          = RespH.SRV_NOTIF_CARD_FAVORITED,
                                CardId        = currentCard.Id,
                                FromUserName  = profile.FirstName,
                                FromUserEmail = user.Email,
                                ToUserName    = currentCard.User.Profile.FirstName,
                                ToUserEmail   = currentCard.User.Email,
                                UnsubscrCode  = currentCard.User.EmailSubCode
                            };
                            mailSender.Create(_context, bem);
                        }
                    }
                    status = true;
                }
                else
                {
                    var notif = _context.Notifications.SingleOrDefault(n => n.FavoriteId == favorite.Id);
                    if (notif != null)
                    {
                        _context.Notifications.Remove(notif);
                    }
                    _context.SaveChanges();
                    _context.Favorites.Remove(favorite);
                    status = false;
                }
                _context.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.OK,
                                              RespH.CreateBool(RespH.SRV_DONE, new List <bool> {
                    status
                })));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage PostReview(string resId, ReviewDTO review)
        {
            try
            {
                var         respList = new List <string>();
                ResponseDTO resp;

                // Check Card is not NULL
                if (review == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_REVIEW_NULL)));
                }

                // Check Reservation is not NULL
                var reservation = _context.Reservations.AsNoTracking().SingleOrDefault(x => x.Id == resId);
                if (reservation == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_NOTFOUND)));
                }

                // Check Reservation Status is Accepted
                if (reservation.Status != ConstVals.Accepted)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_REVIEW_WRONG_RESERV_STATUS)));
                }

                // Check Reservation Dates
                if (reservation.DateTo >= DateTime.Now)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_REVIEW_WRONG_DATE)));
                }

                // Check Review Text is not NULL
                resp = CheckHelper.IsNull(review.Text, "Text", RespH.SRV_REVIEW_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                // Check Review Rating is not NULL
                //resp = CheckHelper.IsNull(review.Rating, "Rating", RespH.SRV_REVIEW_REQUIRED);
                //if (resp != null) return this.Request.CreateResponse(HttpStatusCode.BadRequest, resp);

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                resp = CheckHelper.IsProfileFill(_context, account.UserId);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                var newReview = new Review();
                // Set FromUserId
                newReview.FromUserId = account.UserId;

                // Set ToUserId
                if (reservation.UserId == account.UserId)
                {
                    newReview.ToUserId = reservation.Card.UserId;
                }
                if (reservation.Card.UserId == account.UserId)
                {
                    newReview.ToUserId = reservation.UserId;
                }

                // Check Review doesn't already exist
                var currentReview =
                    _context.Reviews.AsNoTracking().SingleOrDefault(
                        r =>
                        r.ReservationId == reservation.Id && r.FromUserId == newReview.FromUserId &&
                        r.ToUserId == newReview.ToUserId);
                if (currentReview != null)
                {
                    respList.Add(currentReview.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_REVIEW_EXISTS, respList)));
                }
                var reviewGuid = SequentialGuid.NewGuid().ToString();
                newReview.Id            = reviewGuid;
                newReview.ReservationId = reservation.Id;
                newReview.Text          = review.Text;


                _context.Reviews.Add(newReview);

                string notifCode;
                // Rating Calculation
                if (review.Rating > 0)
                {
                    var profile = _context.Profile.SingleOrDefault(x => x.Id == newReview.ToUserId);
                    if (profile == null)
                    {
                        respList.Add(newReview.ToUserId);
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                      RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                    }
                    newReview.Rating     = review.Rating;
                    notifCode            = RespH.SRV_NOTIF_REVIEW_RATING_ADDED;
                    profile.RatingCount += 1;
                    profile.Score       += newReview.Rating;
                    profile.Rating       = profile.Score / profile.RatingCount;
                }
                else
                {
                    newReview.Rating = 0;
                    notifCode        = RespH.SRV_NOTIF_REVIEW_ADDED;
                }
                _context.SaveChanges();
                // Create Notification
                Notifications.Create(_context, newReview.ToUserId, ConstVals.General, notifCode, null, null, reviewGuid);
                var fromUser    = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                var fromProfile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                var toUser      = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == newReview.ToUserId);
                var toProfile   = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == newReview.ToUserId);
                if (toUser.EmailNewsletter)
                {
                    using (MailSender mailSender = new MailSender())
                    {
                        var bem = new BaseEmailMessage
                        {
                            Code          = notifCode,
                            FromUserName  = fromProfile.FirstName,
                            FromUserEmail = fromUser.Email,
                            ToUserName    = toProfile.FirstName,
                            ToUserEmail   = toUser.Email,
                            ReviewText    = newReview.Text,
                            ReviewRating  = newReview.Rating,
                            UnsubscrCode  = toUser.EmailSubCode
                        };
                        mailSender.Create(_context, bem);
                    }
                }
                respList.Add(reviewGuid);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_CREATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }