#--######################################################################
# Copyright (c) 2006 Logica
# 
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# 
# Onno van der Straaten:: initial implementation
#++######################################################################
# {Copyright (c) 2006 Logica}[link:files/COPYRIGHT.html]

class UploadsController < ApplicationController
  
  layout 'management'
  
  before_filter :authenticate, :except => [:list, :show]
  before_filter :authenticate_admin, :only => [:review, :review_note]
  before_filter :authenticate_cadmin, :only => [:destroy]
  
  def index
    list
    render :action => 'list'
  end
  
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],:add_flash => {'error' => ::FLASH_USE_POST_NOT_GET}, :redirect_to => { :controller => 'other', :action => 'error' }  
  
  def list
    @upload_pages, @uploads = paginate :uploads, :order => 'created_on DESC',  :per_page => 10
  end
  
  def show
    @upload = Upload.find(params[:id])
  end
  
  def new
    if request.get?
      @upload = Upload.new
    else
      @upload = Upload.new(params[:upload].merge(:user => session['user']))
      if @upload.save
        @upload.save_file
        flash[:notice] = 'Upload was successfully created.'
        users = User.find(:all, :conditions => ['notify_immediate=?', 1])
        unless users.empty?
          subject = "New upload from #{@upload.user.name}"
          introduction = "<p>User #{@upload.user.name} uploaded a document or image <a href=\"#{@upload.url(true, request.host + (request.port == 80 ? '' : ':' + request.port.to_s))}\">#{@upload.filename}</a></p>"
          Notifier::deliver_notification(users,subject,introduction, @upload.description, request.host + (request.port == 80 ? '' : ':' + request.port.to_s)) 
        end        
        redirect_to :action => 'list'
        #render :action => 'new'
      end
    end
  end
  
  def edit
    @upload = Upload.find(params[:id])
  end
  
  def update
    @upload = Upload.find(params[:id])
    if mine?(@upload) || admin?
      if @upload.update_attributes(params[:upload])
        flash[:notice] = 'Upload was successfully updated.'
        redirect_to :action => 'list'
      else
        render :action => 'edit'
      end
    else
      flash['error'] = ::FLASH_NOT_OWNER
      render :action => 'edit'
    end
  end
  
  def destroy
    @upload = Upload.find(params[:id])
    @upload.destroy
    redirect_to request.referer
  end
  
end
