module JamRuby
  class IcecastPath < ActiveRecord::Base

    attr_accessible :base_dir, :log_dir, :pid_file, :web_root, :admin_root, :allow_ip, :deny_ip, :alias_source,
                    :alias_dest, as: :admin

    has_many :servers, :class_name => "JamRuby::IcecastServer", :inverse_of => :path, :foreign_key => "path_id"
    has_many :templates, :class_name => "JamRuby::IcecastTemplate", :inverse_of => :path, :foreign_key => "path_id"

    validates :base_dir, presence: true
    validates :log_dir, presence: true
    validates :web_root, presence: true
    validates :admin_root, presence: true

    after_save      :poke_config
    before_destroy  :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
      "base_dir=#{base_dir}"
    end

    def dumpXml (builder)

      builder.tag! 'paths' do |paths|
        paths.tag! 'basedir', base_dir
        paths.tag! 'logdir', log_dir
        paths.tag! 'pidfile', pid_file if !pid_file.nil? && !pid_file.empty?
        paths.tag! 'webroot', web_root
        paths.tag! 'adminroot', admin_root
        paths.tag! 'allow-ip', allow_ip if allow_ip
        paths.tag! 'deny-ip', deny_ip if deny_ip
        paths.tag! 'alias', :source => alias_source, :dest => alias_dest if !alias_source.nil? && !alias_source.empty?
      end
    end
  end
end