module JamRuby
  class IcecastRelay < ActiveRecord::Base

    attr_accessible :server, :port, :mount, :local_mount, :relay_username, :relay_pass, :relay_shoutcast_metadata, :on_demand,
                    as: :admin

    has_many :server_relays, :class_name => "JamRuby::IcecastServerRelay"
    has_many :servers, :class_name => "JamRuby::IcecastServer", :through => :server_relays, :source => :server

    validates :port, presence: true, numericality: {only_integer: true}, length: {in: 1..65535}
    validates :mount, presence: true
    validates :server, presence: true
    validates :relay_shoutcast_metadata,  :inclusion => {:in => [0, 1]}
    validates :on_demand, presence: true, :inclusion => {:in => [0, 1]}

    before_destroy  :poke_config
    after_save      :poke_config

    def poke_config
      servers.update_all(:config_changed => 1)
    end

    def to_s
      mount
    end

    def dumpXml (builder)
      builder.tag! 'relay' do |listen|
        listen.tag! 'server', server
        listen.tag! 'port', port
        listen.tag! 'mount', mount
        listen.tag! 'local-mount', local_mount if !local_mount.nil? && !local_mount.empty?
        listen.tag! 'username', relay_username if !relay_username.nil? && !relay_username.empty?
        listen.tag! 'password', relay_pass if !relay_pass.nil? && !pasword.empty?
        listen.tag! 'relay-shoutcast-metadata', relay_shoutcast_metadata
        listen.tag! 'on-demand', on_demand
      end
    end
  end
end