public void UpdatePhoto(Photo photo)
 {
     _photoRepo.UpdatePhoto(photo);
     _baseService.Cacher.RemoveAll(new List<string> {PHOTOS_OWNER.Fmt(photo.OwnerId), PHOTO_ID.Fmt(photo.PhotoId)});
 }
 public bool PhotoTypeExist(Photo photo, PhotoType photoType)
 {
     return photo.PhotoTypes.Any(tf => tf.PhotoTypeId == photoType.PhotoTypeId);
 }
        public Photo RemovePhotoTypeFromPhoto(Photo photo, int photoTypeId)
        {
            if (photo.PhotoTypes != null)
            {
                if (photo.PhotoTypes.Any(pt => pt.PhotoTypeId == photoTypeId))
                {
                    var ptIndex = 0;
                    for (int i = 0; i < photo.PhotoTypes.Count; i++)
                    {
                        if (photo.PhotoTypes[i].PhotoTypeId == photoTypeId)
                        {
                            ptIndex = i;
                            break;
                        }
                    }

                    var typeImagePath = photo.GetPhotoUrl(photoTypeId);
                    photo.PhotoTypes.RemoveAt(ptIndex);

                    try
                    {
                        DeletePhotoTypeImage(HttpContext.Current.Server.MapPath(typeImagePath));
                        _photoRepo.UpdatePhoto(photo);
                        _baseService.Cacher.RemoveAll(AllCacheKeys(photo));
                    }
                    catch
                    {
                        throw;
                    }
                }
            }

            return photo;
        }
        public List<OrigPhotosWaiting> GetWaitingPhotos(Owner owner, string subDir)
        {
            var retColl = new List<OrigPhotosWaiting>();
            var currentUserDir = HttpContext.Current.Server.MapPath(string.Format("{0}/{1}",
                                                                    _baseService.AppConfig.GalleryImagesRoot,
                                                                    owner.OwnerDirectory ));

            var uploadPath = string.Format(@"{0}\{1}", currentUserDir, _baseService.AppConfig.UploadDirName);

            if (!string.IsNullOrEmpty(subDir))
            {
                uploadPath = string.Format(@"{0}\{1}", uploadPath, subDir);
            }

            var files = GetFilesInDirectory(uploadPath);
            if (files.Length > 0)
            {
                var uploadType = _photoRepo.GetBySystemName("upload");
                var adminThumb = _photoRepo.GetBySystemName("adminthumb");
                uploadType.Directory = uploadType.Directory + @"\" + subDir;

                for (int i = 0; i < files.Length; i++)
                {
                    var photoAlreadyInDb = GetPhotoByFileName(files[i].Name);

                    string fileName;
                    int photoId;

                    if (photoAlreadyInDb == null) //fotku sme jeste nezpracovavali
                    {
                        fileName = RenameToSystemFileName(files[i].FullName);
                        var fotka = new Photo
                            {
                                FileName = fileName,
                                OwnerId = owner.OwnerId,
                                DateUploaded = files[i].CreationTime,
                                DateCreated = DateTime.Now,
                                PhotoTypes = new List<PhotoType>{uploadType},
                                Owner = owner,
                                BasePhotoVirtualPath = _baseService.AppConfig.GalleryImagesRoot
                            };

                        photoId = InsertPhoto(fotka);
                        fotka.PhotoId = photoId;

                        try
                        {
                            ImageProcessingService.ResizeImage(fotka, uploadType, adminThumb);
                            AddPhotoTypeToPhoto(fotka, adminThumb);
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                    else
                    {
                        fileName = photoAlreadyInDb.FileName;
                        photoId = photoAlreadyInDb.PhotoId;
                    }

                    var photoWaiting = new OrigPhotosWaiting { FileName = fileName, UploadedDate = files[i].CreationTime, PhotoId = photoId};

                    //X,Y dimensions of originally uploaded photo - uncomment if you need to diplay it on ProcessUploadPhotos view.

                    //var origPath = HttpContext.Current.Server.MapPath(string.Format("/{0}/{1}/{2}/{3}", ConfigurationManager.AppSettings["GalleryRootDirVirtualPath"], currentUserDir, uploadType.Adresar, fileName));
                    //var origDimensions = ImageProcessingManager.GetImageDimensions(origPath);
                    //photoWaiting.X = origDimensions[0];
                    //photoWaiting.Y = origDimensions[1];

                    photoWaiting.ThumbPath = string.Format("{0}/{1}/{2}/{3}", _baseService.AppConfig.GalleryImagesRoot, owner.OwnerDirectory, adminThumb.Directory, fileName);

                    retColl.Add(photoWaiting);
                }
            }
            return retColl;
        }
        /*
        public List<GalleryPhoto> GetPhotos(Dictionary<ObjectId, int> photoIds)
        {
            if (photoIds != null && photoIds.Any())
            {
                var retColl = photoIds.Select(photoId => new GalleryPhoto(GetPhoto(photoId.Key), photoId.Value)).ToList();
                return retColl;
            }

            return null;
        }

        public void MovePhotoSiblingsToTrash(User owner)
        {
            var photos = _photos.Collection.FindAll();
            if (photos != null && photos.Any())
            {
                var galleryManager = new GalleryManager();
                var trashGallery = galleryManager.GetTrashGallery(owner);
                var siblings = (from photo in photos where !galleryManager.IsPhotoInGallery(photo.Id) select photo.Id.ToString()).ToList();

                if (siblings.Count > 0)
                {
                    galleryManager.AddPhotosToGallery(trashGallery.Id.ToString(), siblings.ToArray());
                }
            }
        }

         */
        public int InsertPhoto(Photo photo)
        {
            _baseService.Cacher.Remove(PHOTOS_OWNER.Fmt(photo.OwnerId));
            return _photoRepo.InsertPhoto(photo);
        }
 public void ResizeImage(Photo photo, PhotoType fromType, PhotoType targetType, string savePath)
 {
     using (var thumb = DoResizeImage(photo, fromType, targetType))
     {
         if (string.IsNullOrEmpty(savePath))
         {
             SaveImage(thumb, photo, targetType);
         }
         else
         {
             SaveImage(thumb, savePath, photo.FileName);
         }
     }
 }
        /// <summary>
        /// Will create specific photo type and returns it's path as "{0}/{1}", photoType.Directory, photo.FileName
        /// </summary>
        /// <param name="photo"></param>
        /// <param name="photoType"></param>
        /// <returns>Path as "{0}/{1}", photoType.Directory, photo.FileName</returns>
        public string CreateTypeOfPhoto(Photo photo, PhotoType photoType)
        {
            if (photoType.SystemName.ToLower() != "orig")
            {
                var origType = _photoRepo.GetBySystemName("orig");
                try
                {
                    ImageProcessingService.ResizeImage(photo, origType, photoType);
                    AddPhotoTypeToPhoto(photo, photoType);
                }
                catch
                {
                    throw;
                }
            }

            return string.Format("{0}/{1}", photoType.Directory, photo.FileName);
        }
 public void UpdatePhoto(Photo photo)
 {
     Update(photo);
 }
        /*

        public void Delete(Photo photo)
        {
            _photos.Collection.Remove(Query.EQ("_id", photo.Id));
        }

        public Photo CreateFotka(string ownerId, string fullFileName, DateTime dateUploaded)
        {
            string photoSystemName;

            try
            {
                photoSystemName = RenameToSystemFileName(fullFileName);
            }
            catch (Exception ex)
            {
                throw;
            }

            var photoToSave = new Photo { FileName = photoSystemName, OwnerId = new ObjectId(ownerId), DateUploaded = dateUploaded };
            Save(photoToSave);

            return GetPhoto(photoToSave.Id);
        }

         */
        public Photo AddPhotoTypeToPhoto(Photo photo, PhotoType photoType)
        {
            var doSave = false;

            if (photo.PhotoTypes == null)
            {
                photo.PhotoTypes = new List<PhotoType> { photoType };
                doSave = true;
            }
            else
            {
                if (photo.PhotoTypes.All(p => p.SystemName.ToLower() != photoType.SystemName.ToLower()))
                {
                    photo.PhotoTypes.Add(photoType);
                    doSave = true;
                }
            }

            if (doSave)
            {
                _photoRepo.UpdatePhoto(photo);
                _baseService.Cacher.RemoveAll(AllCacheKeys(photo));
            }

            return photo;
        }
        public string GetPhotoFullPath(Photo photo, PhotoType photoType)
        {
            if (photo == null || photoType == null) { throw new ArgumentException("Missing Photo or PhotoType"); }

            if (photo.PhotoTypes != null && photo.PhotoTypes.Any(f => f.SystemName.ToLower() == photoType.SystemName.ToLower()))
            {
                var typeFolder = photo.PhotoTypes.First(f => f.SystemName.ToLower() == photoType.SystemName.ToLower()).Directory;
                return HttpContext.Current.Server.MapPath(string.Format("{0}/{1}/{2}/{3}", photo.BasePhotoVirtualPath, photo.Owner.OwnerDirectory, typeFolder, photo.FileName));
            }

            throw new Exception(string.Format("Original photo not defined for Photo Id: {0}!", photo.PhotoId));
        }
 public int InsertPhoto(Photo photo)
 {
     return Insert(photo);
 }
 public int[] GetImageDimensions(Photo photo, PhotoType photoType)
 {
     var fullPath = GetPhotoFullPath(photo, photoType);
     return GetImageDimensions(fullPath);
 }
        private void SaveImage(Bitmap thumbImage, Photo photo, PhotoType targetType)
        {
            var targetTypeDirectory = HttpContext.Current.Server.MapPath(string.Format(@"{0}\{1}\{2}", photo.BasePhotoVirtualPath, photo.Owner.OwnerDirectory, targetType.Directory));

            SaveImage(thumbImage, targetTypeDirectory, photo.FileName);
        }
        private Bitmap DoResizeImage(Photo photo, PhotoType fromType, PhotoType targetType)
        {
            var fullPath = GetPhotoFullPath(photo, fromType);
            var origImage = LoadImage(fullPath);

            int resX = targetType.X;
            int resY;
            float ratio;

            //TODO: tady je chyba!!!!!! + tahle metoda se vola divne moc casto ???

            if (targetType.Y.HasValue) //mam zadanou vysku
            {
                resY = targetType.Y.Value;

                if (resX == resY) //ctvercova transformace
                {
                    return MakeSquareTransfrom(resX, resY, origImage);
                }
            }

            //obrazek na sirku nebo ctverec:
            if (origImage.Width >= origImage.Height)
            {
                ratio = (float)origImage.Height / (float)origImage.Width;
                resY = Convert.ToInt32(resX * ratio);
            }
            else //obrazek na vysku.
            {
                if(targetType.Y.HasValue) //mam zadanou vysku
                {
                    resY = targetType.Y.Value;
                    ratio = (float)origImage.Width / (float)origImage.Height;
                    resX = Convert.ToInt32(resY * ratio);
                }
                else //pokud nemam zadanou vysku, musim to resizovat podle zadane sirky
                {
                    ratio = (float)origImage.Height / (float)origImage.Width;
                    resY = Convert.ToInt32(resX * ratio);
                }
            }

            var thumbImage = new Bitmap(resX, resY, origImage.PixelFormat);
            Graphics g = Graphics.FromImage(thumbImage);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;

            var oRectangle = new Rectangle(0, 0, resX, resY);
            g.DrawImage(origImage, oRectangle);

            if (resX < origImage.Width)
            {
                var si = new SharpeningImage();
                si.Filter(thumbImage);
            }

            origImage.Dispose();

            return thumbImage;
        }
 private IEnumerable<string> AllCacheKeys(Photo photo)
 {
     return new List<string>
         {
             PHOTOS_OWNER.Fmt(photo.OwnerId),
             PHOTO_FILENAME.Fmt(photo.FileName),
             PHOTO_ID.Fmt(photo.PhotoId)
         };
 }
 public string CreateTypeOfPhoto(Photo photo, int photoTypeId)
 {
     var type = GetByPhotoTypeId(photoTypeId);
     if (type != null)
     {
         return CreateTypeOfPhoto(photo, type);
     }
     return "";
 }
        private Photo PostProcessPhoto(Photo photo)
        {
            if (photo != null)
            {
                photo.BasePhotoVirtualPath = _baseService.AppConfig.GalleryImagesRoot;
                photo.Owner = UserService.GetOwnerById(photo.OwnerId);
                return photo;
            }

            return null;
            //throw new Exception("Photo is null!");
        }
        public void ResizeImage(Photo photo, PhotoType fromType, PhotoType targetType)
        {
            if(PhotoTypeExist(photo, targetType))
            {
                var photoTypeFileName = GetPhotoFullPath(photo, targetType); //photo.GetPhotoUrl(targetType.SystemName);

                if(File.Exists(photoTypeFileName))
                {
                    return;
                }
            }

            ResizeImage(photo, fromType, targetType, null);
        }