module JamRuby
  class IcecastMasterServerRelay < ActiveRecord::Base

    attr_accessible :master_server, :master_server_port, :master_update_interval, :master_username, :master_pass,
                    :relays_on_demand, as: :admin

    has_many :servers, :class_name => "JamRuby::IcecastServer", :inverse_of => :master_relay, :foreign_key => "master_relay_id"
    has_many :templates, :class_name => "JamRuby::IcecastTemplate", :inverse_of => :master_relay, :foreign_key => "master_relay_id"

    validates :master_server, length: {minimum: 1}
    validates :master_server_port, presence: true, numericality: {only_integer: true}, length: {in: 1..65535}
    validates :master_update_interval, presence: true, numericality: {only_integer: true}, length: {in: 1..1200}
    validates :master_username, presence: true, length: {minimum: 5}
    validates :master_pass, presence: true, length: {minimum: 5}
    validates :relays_on_demand, :inclusion => {:in => [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
      "master_server=#{master_server} master_server_port=#{master_server_port} master_username=#{master_username}"
    end

    def dumpXml(builder)
        builder.tag! 'master-server', master_server
        builder.tag! 'master-server-port', master_server_port
        builder.tag! 'master-update-interval', master_update_interval
        builder.tag! 'master-username', master_username
        builder.tag! 'master-password', master_pass
        builder.tag! 'relays-on-demand', relays_on_demand
    end
  end
end