class VBda < ApplicationRecord
  belongs_to :volume_periodique
  belongs_to :v_contact
  belongs_to :societe
  
  
  
  include ActionView::Helpers::NumberHelper
  include ActionView::Helpers::TranslationHelper
  #include ActionView::Helpers::UrlHelper
  
  include Rails.application.routes.url_helpers
  
  
  before_validation do
    if !self.token?
      generate_token(:token)
    end
    self.date = Date.today if !self.date
    
    self.end_at = self.date + 1.year
    self.societe = self.v_contact.societe
    
    if !self.id and self.bda_type == "ri"
      self.seuil = self.amount / (self.societe.remise_percent/100.0)
      
      errors.add(:amount, "Ne peut pas être suppérieur à #{max_amount} euros") if self.amount > max_amount
    end
  end
  
  def max_amount
    self.v_contact.max_ri_amount
  end

  before_create do
    volume_periodique = VolumePeriodique.new(:commentaire => "", :super_admin_power => true, :v_contact => self.v_contact, :societe => self.societe, :v_contact => self.v_contact, :valeur => (self.seuil*-1), :datedebut => self.created_at)
    
    if self.bda_type == "bda"
      volume_periodique.commentaire = "Régul seuil | Génération bon d'achat #{self.token}"
    else
      volume_periodique.commentaire = "Régul seuil | Remise immédiate de #{self.amount}€ | #{self.token}"
    end
    volume_periodique.save
    self.volume_periodique = volume_periodique
    
    self.update_info
  
  end
  
  def update_info
    self.send_via = self.v_contact.societe.send_via if self.bda_type == "bda"
    self.email = self.v_contact.mailto if self.bda_type == "bda"
  end
  
  after_commit do
    self.generate_ba
    self.generate_pdf
  end

  def generate_token(column)
    begin
        self[column] = ("RI" if self.bda_type == "ri").to_s+SecureRandom.hex(4).upcase
    end while VBda.exists?(column => self[column])
  end


  acts_as_sorting :fields => {
     :id => {:name => "Id", :reorder => true},
     :token => {:name => "N°", :reorder => true},
     :date => {:name => "Date", :reorder => true},
     :amount => {:name => "Montant", :reorder => true, :as => :currency},
     :seuil => {:name => "Seuil", :reorder => true, :as => :currency},
     :used => {:name => "Utilisé ?", :reorder => true, :as => :boolean},
     :end_at => {:name => "Date de fin de validité", :reorder => true},
     :v_contact => {:name => "Carte", :reorder => true},
     :societe_id => {:name => "Centre", :reorder => true},
     #:societe_use_id => {:name => "Societe_use_id", :reorder => true},
     :comment => {:name => "Commentaire", :reorder => true},
     :bda_type => {:name => "Type", :reorder => true},
     :send_via => {:name => "Méthode d'envoi", :reorder => true},
     :email => {:name => "Email", :reorder => true},
     :sended => {:name => "Email envoyé ?", :reorder => true, :as => :boolean},
     #:created_at => {:name => "Created_at", :reorder => true},
     #:updated_at => {:name => "Updated_at", :reorder => true},
     :actions => {:name => "Actions", :reorder => true}
  }
  
  
  def generate_ba
    
    
    
    
    doc_number = self.token
    url = "/admin/v_bdas/#{self.id}/ba"
    
    
    
    @temp_file = "#{Rails.root}/public/public_medias/#{doc_number}.png"
    
    if !File.exist?(@temp_file)
     
      url = (Rails.env.development? ? "http://localhost:3000" : "https://loyaltyprog.market-inn.fr").to_s+url
      puts url
      pdf = ("ba")
    
      node_file = @temp_file
    
      req = "node #{pdf}.js #{Shellwords.escape(url)} #{Shellwords.escape(@temp_file)} 564 566"
      puts "AAA"
      puts req
      system(req)
  
    
      
      require 'posix/spawn'
    
    end
  
    
    return @temp_file
    
    
    
  end
  
  def ba_url
    
    
    url = (Rails.env.development? ? "http://localhost:3000" : "https://loyaltyprog.market-inn.fr").to_s+"/public_medias/#{self.token}.png"
    
  end
  
  def ba_pdf_url
    
    
    url = (Rails.env.development? ? "http://localhost:3000" : "https://loyaltyprog.market-inn.fr").to_s+"/public_medias/#{self.token}.pdf"
    
  end
  
  
  def generate_pdf


    

    doc_number = self.token
    url = ba_pdf_admin_v_bda_path(:id => self.id, :print => true)


    @temp_file =   "#{Rails.root}/public/public_medias/#{doc_number}_temp.pdf"
    @final_file =  "#{Rails.root}/public/public_medias/#{doc_number}.pdf"
    #@final_file2 = "#{Rails.root}/public/public_medias/#{doc_number}.pdf"

    if !File.exist?(@final_file)
      url = (Rails.env.development? ? "http://localhost:3000" : "https://loyaltyprog.market-inn.fr").to_s+url
      puts url
      pdf = ("pdf")

      node_file = @temp_file

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

    

      require 'posix/spawn'

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

    end

    return @final_file



  end
  
  def send_mail_type(slug, element = nil)
    if self.bda_type == "bda" and self.send_via == "Mail" and self.email?
    
    
      mail_hist = MailHist.auto_generate_mail(:fr, slug, self.email, {:arguments => {:numero_bon_achat => self.token, :bon_achat => ("<center><img src='#{self.ba_url}' style='display:block;margin;auto;' /></center>"), :remise => number_to_currency(self.amount.to_f), :civilite => self.v_contact.civilite, :nom => self.v_contact.nom, :prenom => self.v_contact.prenom  }, :v_bda => self, :v_contact => self.v_contact, :societe => self.societe, :element => self})
      self.sended = true
      self.save
    
    end
  end
  
  def csv_societe_id
    self.societe.nom if self.societe
  end
  
  def csv_v_contact
    "#{self.v_contact.codemanaginn} - #{self.v_contact.nom} #{self.v_contact.prenom}" if self.v_contact
  end
  
  
  
end
