class Public::DocumentsController < ApplicationController

  layout "public"

  before_filter :auth_customer
  before_filter :check_enabled
  before_filter :load_accepted_offer, except: [:download]


  def load_accepted_offer
    @accepted_offer = AcceptedOffer.find(params[:accepted_offer_id])
  end

  def index

    @documents = @accepted_offer.documents

  end


  def download
     @document = Document.find_by_download_token!(params[:download_token])

    if !params[:admin]
      if @document.state == 'document_available'
        @document.state = :document_downloaded
        @document.save

        admins = Admin.where.not(email: nil)
        admins.each do |admin|
          AdminMailer.customer_download_document(admin,   @document, current_customer).deliver
        end
      end
    end
    if @document.particulars

      send_data File.open(@document.get_particularized_document_file_path).read  , :filename =>"negos-document-#{@document.id}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")

      #render :inline => "j"
    else
      send_file @document.document.file.path
    end

  end

  def download_returned
    @document = @accepted_offer.documents.find(params[:id])
    send_file @document.returned_document.file.path

  end

  def destroy_returned
    @document = @accepted_offer.documents.find(params[:id])
    if @document.returned_document?
      @document.remove_returned_document!
    end
    @document.state = :document_downloaded
    if @document.save
      flash[:success] = "Document chargé"
    else
      flash[:success] = "Impossible de supprimer le document"
    end
    redirect_to :back

  end


  def upload_returned
    if !params[:returned_document]
      flash[:error] = "Vous devez sélectionner un fichier"
    else

      @document = @accepted_offer.documents.find(params[:id])
      @document.returned_document = params[:returned_document]
      if @document.save
        @document.state = :document_returned
        @document.save
        admins = Admin.where.not(email: nil)
        admins.each do |admin|
          AdminMailer.customer_upload_document(admin,   @document, current_customer).deliver
        end
        flash[:success] = "Document chargé"
      else
        flash[:error] = "Impossible de charger le document"
      end
    end
    redirect_to :back

  end


end
