# -*- encoding : utf-8 -*-

class Admin::PDocumentsController < ApplicationController
	#before_filter :auth_admin

	#layout "admin"

  before_filter :admin_space
  
  def admin_space
    @admin_space = "documents"
  end

  def index
    @p_documents = PDocument.order("created_at DESC")
    
    @p_documents = @p_documents.where(:p_document_type_id => params[:p_document_type_id]) if params[:p_document_type_id]
    
    @p_documents = @p_documents.all
    render :layout => "admin"
  end
  
	def show
		@p_document = PDocument.find_by_token(params[:id])
    @element = @p_document.element
    #params[:inline] = true
    if false
    
      @temp_file = "#{Rails.root}/pdf/p_documents/#{@p_document.d_number}_temp.pdf"
      @final_file = "#{Rails.root}/pdf/p_documents/#{@p_document.d_number}.pdf"
  
  
      view = ActionView::Base.new(Rails.root.join('app/views'))
      view.class.include ApplicationHelper
      view.class.include Rails.application.routes.url_helpers

      pdf = view.render( 
              :pdf => "#{@p_document.element.id}",
              :template => "admin/p_documents/show.html.haml",  
            
              :locals => {:@element => @element, :@p_document => @p_document})
                                        
      # then save to a file
      pdf = WickedPdf.new.pdf_from_string(pdf, :margin =>  {   top:               0,                     # default 10 (mm)
                                          bottom:            0,
                                          left:              0,
                                          right:             0 })

      save_path = @temp_file
      File.open(save_path, 'wb') do |file|
      file << pdf
      end
      
      if @p_document.p_document_type.data_file
    
    
   
        require 'posix/spawn'
   
        ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'background', @p_document.p_document_type.data_file.file.path, 'output',  @final_file
  
        #pdftk /Users/nico/Desktop/Sanstitre4.pdf background /Users/nico/Dev/negos_app/pdf_stamp/bl.pdf output sortie.pdf
    
    
    
    
    
        @data_to_send = File.open( @final_file).read
      else
        
        require 'posix/spawn'
   
        ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'background', "#{Rails.root}/pdf_stamp/en-tete.pdf", 'output',  @final_file
        
        @data_to_send = File.open( @final_file).read
      end
    
      send_data @data_to_send, :filename =>"#{@p_document.d_number}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")

    
    else
      render :layout => false
    end
    
	end


  
end