class Admin::ArtworksController < ApplicationController
  layout "admin"
  
  before_filter :auth_admin
  
	def reorder
		i = 0
		params[:order].each do |artwork_id|
			i += 1
			artwork = Artwork.find(artwork_id)
			artwork.position = i
			artwork.save
		end
		
	end
  
  def index
    
    @artworks = Artwork.all
  end


  def show
    @artwork = Artwork.find(params[:id])

  end


  def new
    @artwork = Artwork.new
  
  end

  def edit
    @artwork = Artwork.find(params[:id])
  
  end

	def create
	  title = File.basename(params[:files].original_filename.to_s, File.extname(params[:files].original_filename.to_s)).capitalize.to_s if params[:files]
      
      
    @artwork_image = ArtworkImage.new :image =>params[:files], :artwork_id => params[:artwork_id]
    
    if @artwork_image.save
      
      if !params[:artwork_id]
        @artwork = Artwork.new(:portfolio_id => params[:portfolio_id], :artwork_image => @artwork_image, :title => title)
      
        @artwork.artwork_images << @artwork_image
      
      
	
    		if @artwork.save

    		else

    		end
      else
        @artwork = @artwork_image.artwork
      
      end
      
    end


	end
  

  def update
  	@artwork = Artwork.find(params[:id])
    
    if @artwork.update_attributes(artwork_params)

          
  	else
  		render :action => "edit" 
  	end
    
  end
  		


  def destroy
    @artwork = Artwork.find(params[:id])
    
  	if params[:artwork_image_id]
      @artwork_image = ArtworkImage.find(params[:artwork_image_id])
      @artwork_image.destroy
      @artwork.reload
    else
      
      @artwork.destroy
    end
  
  end
  
  private
      def artwork_params
        params.require(:artwork).permit(:title, :description, :artwork_image_id)
      end



end
