module JamRuby
  class IcecastListenSocket < ActiveRecord::Base

    attr_accessible :port, :bind_address, :shoutcast_mount, :shoutcast_compat, as: :admin

    has_many :server_sockets, :class_name => "JamRuby::IcecastServerSocket", :inverse_of => :socket, :foreign_key => 'icecast_listen_socket_id'
    has_many :servers, :class_name => "JamRuby::IcecastServer", :through => :server_sockets

    has_many :template_sockets, :class_name => "JamRuby::IcecastTemplateSocket",  :inverse_of => :socket, :foreign_key => 'icecast_listen_socket_id'
    has_many :templates, :class_name => "JamRuby::IcecastTemplate", :through => :template_sockets

    validates :port,  presence: true, numericality: {only_integer: true}, length: {in: 1..65535}
    validates :shoutcast_compat, :inclusion => {:in => [nil, 0, 1]}

    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
      "port=#{port} bind_address=#{bind_address}"
    end

    def dumpXml (builder)
      builder.tag! 'listen-socket' do |listen|
        listen.tag! 'port', port
        listen.tag! 'bind-address', bind_address if !bind_address.nil? && !bind_address.empty?
        listen.tag! 'shoutcast-mount', shoutcast_mount if shoutcast_mount
        listen.tag! 'shoutcast-compat', shoutcast_compat if shoutcast_compat
      end
    end
  end
end