class DonatorTransaction < ActiveRecord::Base
  belongs_to :donator
  belongs_to :recurrent_payment
  belongs_to :tr_occasion
  belongs_to :tr_activity
  belongs_to :lang_site
  belongs_to :recurrent_date
  
  #has_many :particulars, :as => :owner
  
  belongs_to :particular_bill, :class_name => "Particular"
  
  accepts_nested_attributes_for :particular_bill
  
  belongs_to :particular_send, :class_name => "Particular"
  
  accepts_nested_attributes_for :particular_send
  
  BANK_ACCOUNT = ["Crédit coopératif", "La banque postale"]
  
  has_many :tr_payments
  belongs_to :tr_payment_ok, :class_name => "TrPayment"
  #accepts_nested_attributes_for :tr_payment
  
  #has_one :tr_payment_type, :through => :tr_payment
  
  has_many :transaction_items
  accepts_nested_attributes_for :transaction_items
  
  
  has_one :generated_recurrent_payment, :foreign_key => :origine_transaction_id, :class_name => "RecurrentPayment"
  accepts_nested_attributes_for :generated_recurrent_payment
  
  
	scope :after, lambda { |date|
	        where("(donator_transactions.created_at >= ?)", date )
	    }
	scope :before, lambda { |date|
	        where("(donator_transactions.created_at <= ?)", date )
	    }
  
  
  def total
    self.transaction_items.sum(:amount)
  end
  
  def total_recu
    self.transaction_items.where("transaction_content_type = ? or transaction_content_type = ?  or transaction_content_type = ? ", "TransactionDonate", "TransactionSponsorship", "TransactionJoin").sum(:amount)
  end
  
  
  def generate_recu
    
    
    if self.paid and self.paid_at? and !self.recurrent and self.tr_payment_ok.tr_payment_type_id == 3 and !self.recu_ok
      index = 0
      if last_dt = DonatorTransaction.where(:recurrent => false, :paid => true, :tr_payment_type_id => 3).where("paid_at >= ? and paid_at <= ?",self.paid_at.beginning_of_year , self.paid_at.end_of_year).where("id != ?", self.id).order("recu_index DESC").first
        index = last_dt.recu_index.to_i
        
      end
      
      index = index + 1
      
      
      
    end
    
    self.recu_index = index
    self.recu_year = self.paid_at.year
    
    self.recu_number = "W"+self.recu_year.to_s+('%07d' % self.recu_index)
    
    self.recu_ok = true
    self.save
    self.recu_number
  end
  
  
  
  def generate_facture
    
    
    if self.paid and self.paid_at? and !self.recurrent and self.tr_payment_ok.tr_payment_type_id == 3 and !self.facture_ok
      index = 0
      if last_dt = DonatorTransaction.where(:recurrent => false, :paid => true, :tr_payment_type_id => 3).where("id != ?", self.id).order("facture_index DESC").first
        index = last_dt.facture_index.to_i
        
      end
      
      index = index + 1
      
      
      
    end
    
    self.facture_index = index

    
    self.facture_number = "W"+('%07d' % self.facture_index)
    
    self.facture_ok = true
    self.save
    self.facture_number
  end
  
  
  
  def create_recurrent_payment
    
    self.generated_recurrent_payment = RecurrentPayment.new()

    
    if self.recurrent and self.tr_payment_ok and self.tr_payment_ok.tr_payment_type_id == 3
      self.generated_recurrent_payment.active = true
      
      if self.tr_payment_ok.paid_at?
        
        date = self.tr_payment_ok.paid_at

        if date.day < 10
          next_date = date.next_month.beginning_of_month + 9.days
        else
          next_date = date.next_month.next_month.beginning_of_month + 9.days
        end
        
        
        #self.generated_recurrent_payment.ogone_alias = self.tr_payment_ok.ogone_alias
        #self.generated_recurrent_payment.ogone_cb_expiration = self.tr_payment_ok.ogone_cb_expiration
        #self.generated_recurrent_payment.ogone_brand = self.tr_payment_ok.ogone_brand
        #self.generated_recurrent_payment.ogone_subbrand = self.tr_payment_ok.ogone_subbrand
        #self.generated_recurrent_payment.ogone_cn = self.tr_payment_ok.ogone_cn
        #self.generated_recurrent_payment.ogone_cardno = self.tr_payment_ok.ogone_cardno
        #self.generated_recurrent_payment.infos_ok = true
        
        self.generated_recurrent_payment.start_at = next_date
        
      end
      
    else
      self.generated_recurrent_payment.active = false
      self.generated_recurrent_payment.start_at = nil
    end
  end
  
  
  def valid_particulars?
    
    true if self.particular_bill.valid? and particular_send.valid?
  
    
  end

  
  def prodons_payment_mode
    if self.tr_payment_ok and self.tr_payment_ok.tr_payment_type_id == 3
      if self.recurrent
        "CBREG"
      else
        "CB"
      end
      
    elsif self.tr_payment_ok and self.tr_payment_ok.tr_payment_type_id == 5
      "IBAN"
      
    end
  end
  def prodons_recu_statut
    if (self.recurrent)
      "O"
    else
      "N"
    end
       
  end
  
  def prodons_recu_annuel
    "O" if (self.recurrent)
  end
  
  def prodons_periodicite
    "M" if self.tr_payment_type_id == 5
  end
  
  def prodons_country
    countr = particular_bill.country
    if countr.to_s == "FR"
      
    else
      c = ISO3166::Country.new countr
      c.translation('fr')
    end
  end
  
  
  def prodons_date
    if self.paid_at?
      date = self.paid_at
    else
      date = self.created_at
    end
    
    date.strftime("%d/%m/%Y")
      
  end
  
  
  def prodons_prochain_date
    if self.prochain_date?
      date = self.prochain_date
      date.strftime("%d/%m/%Y")
    end
    
    
      
  end
  
  def prodons_recu_number
    if self.tr_payment_ok.tr_payment_type_id == 3 and !self.recurrent
      self.recu_number
    else
      ""  
    end
    
  end
  
  def occasion
    
    if self.transaction_items[0].transaction_content_type == "TransactionDonate"
      if self.recurrent
        "DONGENE"
      else
        "DONGENE"
      end
      
    elsif self.transaction_items[0].transaction_content_type == "TransactionJoin"
      
      "ADHES+2"
    
    elsif self.transaction_items[0].transaction_content_type == "TransactionAbo"
      if self.tr_payment_ok and self.tr_payment_ok.tr_payment_type_id == 3
        "ABO"
      end
      
    elsif self.transaction_items[0].transaction_content_type == "TransactionSponsorship"
      "PAR."+self.transaction_items[0].transaction_content.sponsorship_animal.code.to_s+(self.recurrent ? ".00" : "" ).to_s
    end
     
  end
  
  def activite
    if self.transaction_items[0].transaction_content_type == "TransactionDonate"
      if self.tr_payment_ok and self.tr_payment_ok.tr_payment_type_id == 3 #CB
        if self.recurrent
          "DONCBREG"
        else
          "DON1"
        end
      
      
      elsif self.tr_payment_ok and self.tr_payment_ok.tr_payment_type_id == 5 #PA
        if self.recurrent
          "DONPA"
        
        end
      
      
      end
    elsif self.transaction_items[0].transaction_content_type == "TransactionJoin"
      if self.tr_payment_ok and self.tr_payment_ok.tr_payment_type_id == 3
        "ADH"+(self.created_at.year-2000).to_s
      end
      
    elsif self.transaction_items[0].transaction_content_type == "TransactionAbo"
      if self.tr_payment_ok and self.tr_payment_ok.tr_payment_type_id == 3
        "ABOW"+self.transaction_items[0].transaction_content.number
      end
      
      
      
      
    elsif self.transaction_items[0].transaction_content_type == "TransactionSponsorship"
      if self.recurrent
        if self.tr_payment_ok and self.tr_payment_ok.tr_payment_type_id == 3 #CB
          "PAR."+self.transaction_items[0].transaction_content.sponsorship_animal.code.to_s+".00"
        elsif self.tr_payment_ok and self.tr_payment_type_id == 5 # PA
          "PAR."+self.transaction_items[0].transaction_content.sponsorship_animal.code.to_s+".00"
        end
      else
        if self.tr_payment_ok and self.tr_payment_ok.tr_payment_type_id == 3 #CB
          nbr_mois = (self.total/10.0).ceil
          "PAR."+self.transaction_items[0].transaction_content.sponsorship_animal.code.to_s+"."+("%02d" % nbr_mois).to_s
        end
        
      end
      
    end
  end
  
  def prodons_bic
    self.bic
  end
  
  def  prodons_iban
    self.iban
  end
    
  
  
  before_validation do
    self.verify
    self.iban = self.iban.to_s.gsub(/\s+/, "")
    
    if self.tr_payment_type_id != 5
      self.iban = ""
      self.bic = ""
    end
    
  end
  
  validates :bic, :presence => true, :if => :iban?
  validates :iban, :presence => true, :if => :iban?
  
  def iban?
    true if self.tr_payment_type_id == 5
  end
  
  before_validation do
    if self.iban?
      unless IBANTools::IBAN.valid?(self.iban)
        self.errors.add :iban, self.errors.generate_message(:iban, :invalid)
      end
    end
    
  end
  
  def check_newsletter
    if self.newsletter and self.particular_bill
  
      Registrant.create(:email => self.particular_bill.email, :donator_transaction_id => self.id) 
      puts "test"
      if @sregistrant = Registrant.find_by_email(self.particular_bill.email) and !@sregistrant.enabled
        @sregistrant.enabled = true
        @sregistrant.validated = true
        @sregistrant.save(:validate => false)
      
      end
    end
  end
  
  
  
  def pay_by_alias
    
  end
  
  def set_abo_numbers
    number = SpecificPreference.find_by_key("noe-en-cours").value.to_i
    numbers = number.to_s+""+(number+3).to_s

    self.transaction_items[0].transaction_content.number = numbers
    self.save
  end
  
  
  protected
  	def verify(size=16)
  		if !self.token
  			s = ""
  			size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
  			self.token = s
		end
	end
   
  
  
end
