class PCommercialObjective < ApplicationRecord
  belongs_to :p_commercial
  has_many :p_commercial_object_months
  accepts_nested_attributes_for :p_commercial_object_months, allow_destroy: true

  has_many :p_commercial_object_cats
  accepts_nested_attributes_for :p_commercial_object_cats, allow_destroy: true

  has_many :p_commercial_object_brands
  accepts_nested_attributes_for :p_commercial_object_brands, allow_destroy: true

  acts_as_sorting :fields => {
    :id => {:name => "Id", :reorder => true},
    :p_commercial => {:name => "Commercial", :reorder => true, :sort_name => "p_commercials.name"},
    :total_ca => {:name => "CA", :reorder => true},
    :start_at => {:name => "Début", :reorder => false},
    :end_at => {:name => "Fin", :reorder => false},
    :actions => {:name => "Actions", :reorder => false}
  }

  after_save :update_p_commercial_object_month
  after_save :update_p_commercial_object_cat
  after_save :update_p_commercial_object_brand

  validates :total_ca, :presence => true
  validates :total_weight, :presence => true

  before_validation :set_end_at

  def set_end_at
    self.end_at = (self.start_at + 1.year) - 1.day
  end

  def long_name
    self.p_commercial.code.to_s+" "+self.p_commercial.firstname.to_s + " " + self.p_commercial.name.to_s
  end

  def update_p_commercial_object_month
    @p_commercial_object_months = PCommercialObjectMonth.where(:p_commercial_objective_id => self.id)
    @p_commercial_object_months.each do |p_commercial_object_month|
      p_commercial_object_month.p_commercial_id = self.p_commercial_id
      p_commercial_object_month.save
    end
  end

  def update_p_commercial_object_cat
    @p_commercial_object_cats = PCommercialObjectCat.where(:p_commercial_objective_id => self.id)
    @p_commercial_object_cats.each do |p_commercial_object_cat|
      p_commercial_object_cat.p_commercial_id = self.p_commercial_id
      p_commercial_object_cat.save
    end
  end

  def update_p_commercial_object_brand
    @p_commercial_object_brands = PCommercialObjectBrand.where(:p_commercial_objective_id => self.id)
    @p_commercial_object_brands.each do |p_commercial_object_brand|
      p_commercial_object_brand.p_commercial_id = self.p_commercial_id
      p_commercial_object_brand.save
    end
  end


  def self.generate_for(year)
    start_at = Date.parse("01/05/#{year}")


    p_commercial_objective = PCommercialObjective.new(:start_at => start_at)

    p_commercial_objective.set_end_at

    end_at = p_commercial_objective.end_at

    start_at = start_at

    while start_at <= end_at
      p_commercial_objective.p_commercial_object_months.build(start_at: start_at)
      start_at = start_at + 1.month
    end

    SBrand.all.each do |ppc|
      p_commercial_objective.p_commercial_object_brands.build(:s_brand_id => ppc.id)
    end

    return p_commercial_objective
  end

end
