class FileTunelDownload < ApplicationRecord
  belongs_to :file_tunel
  belongs_to :file_tunel_send
  
  validates :name, :presence => true
  validates :firstname, :presence => true
  
  before_create { generate_token() }
  
  
  include ActionView::Helpers::NumberHelper
  include ActionView::Helpers::TranslationHelper
  include ActionView::Helpers::UrlHelper
  
  
  def generate_token()
    begin
      self[:token] = SecureRandom.urlsafe_base64
    end while FileTunelDownload.exists?(:token => self[:token])
  end
  
  def lien
    Rails.application.routes.url_helpers.public_file_tunel_download_url(:id => self.token, :slug => self.file_tunel_send.file_tunel .slug, :format => :html)
    
  end
  
  
  def send_mail_type(slug, element = nil)
   
    if self.file_tunel_send and self.file_tunel_send.file_tunel and mail_type = self.file_tunel_send.file_tunel.mail_types.where(:slug => slug).first 
      mail_hist = MailHist.generate_mail(:fr, mail_type, self.file_tunel_send.email, {:arguments => {:nom => self.name, :civilite => self.civilite, :nom => self.name, :prenom => self.firstname, :lien => self.lien  }, :element => self, :file_tunel => self.file_tunel_send.file_tunel})
    end
  end
  
  
  
  
  def generate_pdf
    
    
    
    
    doc_number = self.token
    
    @temp_file = "#{Rails.root}/pdf/price_documents/#{doc_number}_temp.pdf"
    @final_file = "#{Rails.root}/pdf/price_documents/#{doc_number}_temp2.pdf"
    @final_file2 = "#{Rails.root}/pdf/price_documents/#{doc_number}.pdf"
    
   
      
    require 'posix/spawn'
    
    
    
    #::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'stamp', "#{Rails.root}/pdf_stamp/en-tete.pdf", 'output',  @final_file
    
    files = []
    
    self.file_tunel_send.file_tunel.file_tunel_files.order("position ASC").each do |f|
      files << f.file.path if f.file
    end
    
    
      
    puts requette = ['pdftk', files.join(" "), 'cat','output',  @final_file].join(" ")
    system requette
    
    url = Rails.application.routes.url_helpers.fili_public_file_tunel_download_path(:id => self.token,:format => :html)
    
    url = (Rails.env.development? ? "http://localhost:4000" : "https://pollen.olwen.xyz").to_s+url
    puts url
    pdf = ("pdf")

    node_file = @temp_file


    
    

    system("node #{pdf}.js #{Shellwords.escape(url)} #{Shellwords.escape(@temp_file)}")


  
    puts requette = ['pdftk', @final_file, 'stamp', @temp_file, 'output',  @final_file2].join(" ")
    system requette
    
    return @final_file2
    
    
    
  end
  
  
end
