module JamRuby
  class IcecastLimit < ActiveRecord::Base

    attr_accessible :clients, :sources, :queue_size, :client_timeout, :header_timeout, :source_timeout, :burst_size,
                    as: :admin

    has_many :servers, class_name: 'JamRuby::IcecastServer', inverse_of: :limit, foreign_key: 'limit_id'
    has_many :templates, class_name: 'JamRuby::IcecastTemplate', inverse_of: :limit, foreign_key: 'limit_id'

    validates :clients, presence: true, numericality: {only_integer: true}, length: {in: 1..15000}
    validates :sources, presence: true, numericality: {only_integer: true}, length: {in:1..10000}
    validates :queue_size, presence: true, numericality: {only_integer: true}
    validates :client_timeout, presence: true, numericality: {only_integer: true}
    validates :header_timeout, presence: true, numericality: {only_integer: true}
    validates :source_timeout, presence: true, numericality: {only_integer: true}
    validates :burst_size, presence: true, numericality: {only_integer: 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
      "clients=#{clients} sources=#{sources}"
    end

    def dumpXml (builder)

      builder.tag! 'limits' do |limits|
        limits.tag! 'clients', clients
        limits.tag! 'sources', sources
        limits.tag! 'queue-size', queue_size
        limits.tag! 'client-timeout', client_timeout
        limits.tag! 'header-timeout', header_timeout
        limits.tag! 'source-timeout', source_timeout
        limits.tag! 'burst-on-connect', 1
        limits.tag! 'burst-size', burst_size
      end
    end

  end
end
