protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     _vm         = new CreateAnnouncementViewModel();
     DataContext = _vm;
 }
        public async Task <IActionResult> Elanyerleshdir(CreateAnnouncementViewModel createAnnouncementViewModel)
        {
            ViewBag.Estates   = _context.Estates;
            ViewBag.Rooms     = _context.Rooms;
            ViewBag.Durations = _context.Durations;
            ViewBag.Cities    = _context.Cities;

            CustomUser customUserFromDb = await _userManager.FindByNameAsync(User.Identity.Name);

            if (!ModelState.IsValid)
            {
                ViewBag.Estates   = _context.Estates;
                ViewBag.Rooms     = _context.Rooms;
                ViewBag.Durations = _context.Durations;
                ViewBag.Cities    = _context.Cities;

                return(View(createAnnouncementViewModel));
            }

            if (createAnnouncementViewModel.UploadFiles == null || createAnnouncementViewModel.UploadFiles.Count() < 4 || createAnnouncementViewModel.UploadFiles.Count() > 20)
            {
                ViewBag.Estates   = _context.Estates;
                ViewBag.Rooms     = _context.Rooms;
                ViewBag.Durations = _context.Durations;
                ViewBag.Cities    = _context.Cities;

                ModelState.AddModelError("UploadFiles", "Şəkillərin(.jpg, .jpeg) sayı 4-dən az, 20-dən çox ola bilməz");

                return(View(createAnnouncementViewModel));
            }

            foreach (var file in createAnnouncementViewModel.UploadFiles)
            {
                if (file.Length > (2 * 1024 * 1024))
                {
                    ViewBag.Estates   = _context.Estates;
                    ViewBag.Rooms     = _context.Rooms;
                    ViewBag.Durations = _context.Durations;
                    ViewBag.Cities    = _context.Cities;

                    ModelState.AddModelError("UploadFiles", "Şəklin həcmi 2MB'dan çox ola bilməz.");

                    return(View(createAnnouncementViewModel));
                }
            }

            if (createAnnouncementViewModel.BeenReadRules == false)
            {
                ViewBag.Estates   = _context.Estates;
                ViewBag.Rooms     = _context.Rooms;
                ViewBag.Durations = _context.Durations;
                ViewBag.Cities    = _context.Cities;

                ModelState.AddModelError("BeenReadRules", "Diqqət ! Elan yerləşdirmək üçün qaydalarla tanış olmalısınız.");

                return(View(createAnnouncementViewModel));
            }

            //Find the last announcement which doesn't require payment fee
            Announcement lastSimpleAnnouncement = customUserFromDb.Announcements.Where(announce => announce.IsVIP == false && announce.IsDeleted == false && announce.IsBan == false).OrderByDescending(ann => ann.PublishDate).FirstOrDefault();

            if (lastSimpleAnnouncement != null)
            {
                int lastSimpleAnnouncementDayOfYear = lastSimpleAnnouncement.PublishDate.DayOfYear;

                if (lastSimpleAnnouncement.PublishDate.Year == DateTime.Now.Year)
                {
                    if (DateTime.Now.DayOfYear - lastSimpleAnnouncementDayOfYear <= 30)
                    {
                        ViewBag.Estates   = _context.Estates;
                        ViewBag.Rooms     = _context.Rooms;
                        ViewBag.Durations = _context.Durations;
                        ViewBag.Cities    = _context.Cities;

                        TempData["SimpleAnnouncementLimit"] = true;

                        return(View(createAnnouncementViewModel));
                    }
                }
            }

            Announcement announcement = new Announcement
            {
                IsVIP        = createAnnouncementViewModel.IsVIP,
                Details      = createAnnouncementViewModel.Details,
                Price        = createAnnouncementViewModel.Price,
                ViewCount    = 0,
                PublishDate  = DateTime.Now,
                IsActive     = false,
                IsDeleted    = false,
                IsBan        = false,
                EstateId     = createAnnouncementViewModel.EstateId,
                DurationId   = createAnnouncementViewModel.DurationId,
                CityId       = createAnnouncementViewModel.CityId,
                MonthId      = DateTime.Now.Month,
                CustomUserId = customUserFromDb.Id
            };

            if (createAnnouncementViewModel.EstateId == 1 || createAnnouncementViewModel.EstateId == 2)
            {
                announcement.Area        = createAnnouncementViewModel.Area;
                announcement.AreaForView = createAnnouncementViewModel.Area;
                announcement.RoomId      = createAnnouncementViewModel.RoomId;
            }
            else
            {
                announcement.Area        = createAnnouncementViewModel.AreaParticular;
                announcement.AreaForView = createAnnouncementViewModel.AreaParticular;
            }

            await _context.Announcements.AddAsync(announcement);

            await _context.SaveChangesAsync();

            foreach (var file in createAnnouncementViewModel.UploadFiles)
            {
                if (file.ContentType.Contains("image/jpg") || file.ContentType.Contains("image/jpeg"))
                {
                    string folderPath = Path.Combine(_env.WebRootPath, "MainPageFiles", "images", "announcements");
                    fileName = Guid.NewGuid().ToString() + "_elan_" + file.FileName;
                    string filePath = Path.Combine(folderPath, fileName);

                    using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);


                        //Add Watermark
                        //var watermarkedStream = new MemoryStream();
                        //Image image = Image.FromStream(fileStream);
                        //using (Graphics graphic = Graphics.FromImage(image))
                        //{
                        //    SolidBrush brush = new SolidBrush(Color.Black);
                        //    Font font = new Font(FontFamily.GenericSansSerif, 20.0F);
                        //    graphic.DrawString("kirayeemlak.az", font, brush, new PointF(100,100));
                        //    image.Save(fileStream, ImageFormat.Png);
                        //}


                        ////Add Watermark
                        //var watermarkedStream = new MemoryStream();
                        //using (var img = Image.FromStream(fileStream))
                        //{
                        //    using (var graphic = Graphics.FromImage(img))
                        //    {
                        //        var font = new Font(FontFamily.GenericSansSerif, 30.0F, FontStyle.Bold, GraphicsUnit.Pixel);
                        //        var color = Color.Black;
                        //        var brush = new SolidBrush(color);
                        //        var point = new Point(100, 100);

                        //        graphic.DrawString("kirayeemlak.az", font, brush, point);
                        //        img.Save(watermarkedStream, ImageFormat.Png);
                        //    }
                        //}
                    }

                    AnnouncementPhoto announcementPhoto = new AnnouncementPhoto
                    {
                        AnnouncementPhotoURL = fileName,
                        AnnouncementId       = announcement.Id
                    };

                    await _context.AnnouncementPhotos.AddAsync(announcementPhoto);

                    await _context.SaveChangesAsync();
                }
                else
                {
                    ViewBag.Estates   = _context.Estates;
                    ViewBag.Rooms     = _context.Rooms;
                    ViewBag.Durations = _context.Durations;
                    ViewBag.Cities    = _context.Cities;

                    ModelState.AddModelError("UploadFiles", "Zəhmət olmasa, .jpg / .jpeg formatda şəkil yükləyin");

                    _context.Announcements.Remove(announcement);
                    await _context.SaveChangesAsync();

                    return(View(createAnnouncementViewModel));
                }
            }

            TempData["AnnouncementCreated"] = true;

            return(RedirectToAction("Menimhesabim", "Hesab"));
        }