class Admin::CustomImagesController < OrbitAdminController
	before_filter :setup_vars
	def crop_process
	end
	def batch_crop
        images = params['image_ids'].split(',')
        @img = []
		images.each do |image|
			@img << CustomAlbumImage.find(image)
		end
		render 'batch_crop'
	end
	def edit
		@image = CustomAlbumImage.find(params[:id])
		render 'edit_image'
	end
	def show
		@image = CustomAlbumImage.find(params[:id])
		@custom_albumid = @image.custom_album_id
		@custom_album = CustomAlbum.find(@custom_albumid)
		@images = @custom_album.custom_album_images.asc(:order)
	end

	def changeorder
		type = params[:type]
		if type == "imgholder"
			images = params[:imageids]
			images.each_with_index do |image, i|
				img = CustomAlbumImage.find(image) rescue nil
				if !img.nil?
					img.order = i
					img.save 
				end
			end
		elsif type == "orbit_custom_gallery"
			custom_albums = params[:imageids]
			custom_albums.each_with_index do |custom_albumid, i|
				custom_album = CustomAlbum.find(custom_albumid) rescue nil
				if !custom_album.nil?
					custom_album.order = i
					custom_album.save 
				end
			end
		end
    	render :json => {"success" => true}.to_json
  	end

	def delete_photos
		images = params['images']
		images.each do |image|
			img = CustomAlbumImage.find(image)
			begin
				FileUtils.rm_rf(File.dirname(img.file.path))
			rescue => e
				puts ["can't delete",e]
			end
			img.delete
		end
		if params['delete_cover'] == "true"
			custom_album = CustomAlbum.find(params['custom_album_id'])
			custom_album.update_attributes(:cover=>"default",:cover_path => nil)
		end
		render :json =>{"success"=>true}.to_json
	end

	def image_tagging
		images = params[:image_ids]
		tags = params[:tag_ids] || []
		i = nil
		images.each do |image|
			img = CustomAlbumImage.find(image)
			img.tags = tags
			img.save
			i = img
		end
		@custom_album = CustomAlbum.find(i.custom_album_id.to_s)
		@images = @custom_album.custom_album_images
	    @image_content = []
	    @images.each do |image|
	      @image_content << {"id" => image.id.to_s, "description" => image.description_translations,"tags" => image.tags.collect{|t| t.id.to_s}}
	    end
		render :json=>{"custom_galleries" => @image_content}.to_json
	end

	def update_image
		image = CustomAlbumImage.find(params[:image_id])
		image.update_attributes(update_params)
		image.save!
		@custom_album = CustomAlbum.find(image.custom_album_id.to_s)
		@images = @custom_album.custom_album_images
	    @image_content = []
	    @images.each do |image|
	      @image_content << {"id" => image.id.to_s, "description" => image.description_translations,"tags" => image.tags.collect{|t| t.id.to_s}}
	    end
		render :json=>{"custom_galleries" => @image_content}.to_json
	end

	private 

	def setup_vars
  		@module_app = ModuleApp.where(:key=>"custom_gallery").first
	end

	def update_params
		params.require(:custom_album_image).permit!
	end
end