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

class Admin::ProductOrderDocumentsController < ApplicationController
	#before_filter :auth_admin

	#layout "admin"


  
	def show
		@product_order_document = ProductOrderDocument.find_by_token(params[:id])
    @product_order = @product_order_document.product_order
    #params[:inline] = true
    if false
    
      @temp_file = "#{Rails.root}/pdf/bl/DOC_#{@product_order_document.id}_temp.pdf"
      @final_file = "#{Rails.root}/pdf/bl/DOC_#{@product_order_document.id}.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 => "#{@product_order.id}",
              :template => "admin/product_order_documents/show.html.haml",  
            
              :locals => {:@product_order => @product_order, :@product_order_document => @product_order_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 @product_order_document.product_order_document_type.data_file
    
    
   
        require 'posix/spawn'
   
        ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'background', @product_order_document.product_order_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
        @data_to_send = File.open( @temp_file).read
      end
    
      send_data @data_to_send, :filename =>"#{@product_order_document.d_number}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")

    
    else
      render :layout => false
    end
    
	end


  
end
