class MOdrVirement < ApplicationRecord
  belongs_to :m_odr
  belongs_to :m_odr_rep
  belongs_to :m_odr_rep_rib
  belongs_to :m_odr_prime
  belongs_to :m_odr_remise
  
  
  
  
  QI_DYNAMICS = %w(remise iban_to bic_to iban_from bic_from bank_name bank_subject libelle )

  eval(QI_DYNAMICS_CORE)
  
  
  before_create { generate_token() }
  
  
  
  def generate_token()
    begin
      self[:token] = SecureRandom.urlsafe_base64
    end while MOdrVirement.exists?(:token => self[:token])
  end
  
  
  
  def self.qi_table_order
    {
      
      :created_at => {:name => "Date", :reorder => true},
      
      :m_odr_rep_link => {:name => "Prime :"},
      
      :amount =>  {:name => "Montant", :reorder => true},
      :cc_iban_to =>  {:name => "Iban destinataire", :reorder => true},
      :cc_bic_to =>  {:name => "Bic destinataire", :reorder => true},
      :cc_iban_from =>  {:name => "Iban expéditeur", :reorder => true},
      :cc_bic_from =>  {:name => "Bic expéditeur", :reorder => true},
      
      
      
      
      :enabled => {:name => "Ok pour remise ?", :reorder => true},
      
      :sended => {:name => "Validé par la banque ?", :reorder => true},
      
      :refused => {:name => "Refusé par la banque?", :reorder => true},
      
      
      :actions => "Actions",
      
      #:created_at => {:name => "Date", :reorder => true},
      
  
    }
    #, :sort_name => "code"
  end
  
  def ca_remise 
    self.m_odr_prime.amount if self.m_odr_prime
  end
  
  def ca_iban_to 
    self.m_odr_rep_rib.iban if self.m_odr_rep_rib
  end
  
  def ca_bic_to 
    self.m_odr_rep_rib.bic if self.m_odr_rep_rib
  end
  
  def ca_iban_from 
    "IBAN MMSC"
  end
  
  def ca_bic_from 
   "IBAN MMSC"
  end
  
  def ca_bank_name
    self.m_odr_remise.bank_name if self.m_odr_remise
  end
  
  def ca_bank_subject
    self.m_odr_remise.bank_subject if self.m_odr_remise
  end
  
  def ca_libelle
    self.id.to_s+"-"+self.bank_subject if self.bank_subject
  end
  
  
  
  before_validation do
    #self.m_odr = self.m_odr_rep.m_odr if self.m_odr_rep
    
    self.m_odr_rep_rib = self.m_odr_prime.p_customer.m_odr_rep_ribs.where(:admin_ok => true).order("id DESC").first if self.m_odr_prime
    
    self.amount = self.remise
    
  end
  
  
  def self.valid_sort
    r = []
    self.qi_table_order.each do |key, value|
      if value.instance_of? Hash
        if value[:reorder] and value[:reorder] == true
          r << key.to_s if value[:reorder]
        end
      end
    end
    return r
    
    
  end
  
end
