module JamRuby
  class IcecastSecurity < ActiveRecord::Base

    attr_accessible :chroot, :change_owner_user, :change_owner_group, as: :admin

    has_many :servers, :class_name => "JamRuby::IcecastServer", :inverse_of => :security, :foreign_key => "security_id"
    has_many :templates, :class_name => "JamRuby::IcecastTemplate", :inverse_of => :security, :foreign_key => "security_id"

    validates :chroot, :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
      "chroot=#{chroot} change_owner_user=#{change_owner_user} change_owner_group=#{change_owner_group}"
    end

    def dumpXml(builder)
      builder.tag! 'security' do |security|
        security.tag! 'chroot', chroot
        if change_owner_user
          security.tag! 'changeowner' do
            security.tag! 'user', change_owner_user
            security.tag! 'group', change_owner_group
          end
        end
      end
    end
  end
end