module JamRuby
  class IcecastDirectory < ActiveRecord::Base

    attr_accessible :yp_url_timeout, :yp_url, as: :admin

    has_many :servers, :class_name => "JamRuby::IcecastServer", :inverse_of => :directory, :foreign_key => "directory_id"
    has_many :templates, :class_name => "JamRuby::IcecastTemplate", :inverse_of => :directory, :foreign_key => "directory_id"

    validates :yp_url_timeout, presence: true, numericality: {only_integer: true}, length: {in: 1..30}
    validates :yp_url, presence: true

    before_destroy  :poke_config
    after_save      :poke_config

    def poke_config
      servers.update_all(config_changed: 1)
      templates.each { |template| template.servers.update_all(config_changed: 1) }
    end

    def to_s
      yp_url
    end

    def dumpXml (builder)

      builder.tag! 'directory' do |dir|
        dir.tag! 'yp-url-timeout', yp_url_timeout
        dir.tag! 'yp-url', yp_url
      end
    end
  end
end