# -*- 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 !params[:html]
  
      @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"
      
    
      url = (Rails.env.development? ? "http://localhost:4000" : "http://kaps.quartz.xyz").to_s+admin_p_document_path(:id => @p_document.token, :html => true)
      puts url
      pdf = ("pdf")
      system("node #{pdf}.js #{Shellwords.escape(url)} #{Shellwords.escape(@temp_file)}")
  
    
      
      require 'posix/spawn'
  
      if @p_document.p_document_type.data_file 
        ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'background', @p_document.p_document_type.data_file.file.path, 'output',  @final_file

      else
        ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'stamp', "#{Rails.root}/pdf_stamp/en-tete.pdf", 'output',  @final_file
    
      end

      @data_to_send = File.open( @final_file).read

    
      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
