class MusicRelease < ApplicationRecord
  include Confirmable
  include Contractable
  include Exploitable
  include Notable
  include Releasable
  include Searchable
  include Taggable
  include PersonName
  
  has_many :file_infos, as: :releasable, dependent: :destroy
  has_many :composers, dependent: :destroy
  has_many :publishers, dependent: :destroy

  accepts_nested_attributes_for :file_infos
  accepts_nested_attributes_for :composers, reject_if: :all_blank
  accepts_nested_attributes_for :publishers, reject_if: :all_blank

  composed_of :person_address,
    class_name: "Address",
    mapping: [
      %w(person_address_street1 street1),
      %w(person_address_street2 street2),
      %w(person_address_city city),
      %w(person_address_state state),
      %w(person_address_zip zip),
      %w(person_address_country country)
    ]

  validates :name, presence: true
  validates :person_email, email: true, allow_blank: true
  validates :composers, :length => { :minimum => 1, :message => "at least 1 required" }
  validates :publishers, :length => { :minimum => 1, :message => "at least 1 required" }
  validate :publisher_percentages_add_up_to_100
  validate :composer_percentages_add_up_to_100

  searchable_on %i[
    name
    person_address_street1 person_address_street2 person_address_city person_address_state person_address_zip person_address_country
  ]

  def contact_person
    @contact_person ||= Contact.new(person_name, person_address, person_email, person_phone)
  end

  def uses_edl?
    true
  end

  def composer_info
    composers.map do |composer|
      [
        composer.name,
        composer.affiliation,
        composer.percentage,
        ("$cae:#{composer.cae_number}" if composer.cae_number.present?),
      ].compact.join(", ")
    end.join("|")
  end

  def publisher_info
    publishers.map do |publisher|
      [
        publisher.name,
        publisher.affiliation,
        publisher.percentage,
      ].join(", ")
    end.join("|")
  end

  def native?
    false
  end

  private

  def publisher_percentages_add_up_to_100
    if publishers.size > 0 && publishers.sum(&:percentage).to_f != 100.0
      errors.add(:base, "Publisher percentages must add up to 100%")
    end
  end

  def composer_percentages_add_up_to_100
    if composers.size > 0 && composers.sum(&:percentage).to_f != 100.0
      errors.add(:base, "Composer percentages must add up to 100%")
    end
  end
end
