module JamRuby
  class IcecastAdminAuthentication < ActiveRecord::Base

    attr_accessible :source_pass, :relay_user, :relay_pass, :admin_user, :admin_pass, as: :admin

    has_many :servers, :class_name => "JamRuby::IcecastServer", :inverse_of => :admin_auth, :foreign_key => "admin_auth_id"
    has_many :templates, :class_name => "JamRuby::IcecastTemplate", :inverse_of => :admin_auth, :foreign_key => "admin_auth_id"

    validates :source_pass,  presence: true, length: {minimum: 5}
    validates :admin_pass, presence: true, length: {minimum: 5}
    validates :relay_user, presence: true, length: {minimum: 5}
    validates :relay_pass, presence: true, length: {minimum: 5}
    validates :admin_user, presence: true, length: {minimum: 5}

    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
      "admin_user=#{admin_user} relay_user=#{relay_user}"
    end

    def dumpXml (builder)

      builder.tag! 'authentication' do |auth|
        auth.tag! 'source-password', source_pass
        auth.tag! 'admin-user', admin_user
        auth.tag! 'relay-user', relay_user
        auth.tag! 'relay-password', relay_pass
        auth.tag! 'admin-password', admin_pass
      end
    end
  end
end