module JamRuby
  class IcecastLogging < ActiveRecord::Base

    attr_accessible :access_log, :error_log, :playlist_log, :log_level, :log_archive, :log_size, as: :admin

    has_many :servers, :class_name => "JamRuby::IcecastServer", :inverse_of => :logging, :foreign_key => "logging_id"
    has_many :templates, :class_name => "JamRuby::IcecastTemplate", :inverse_of => :logging, :foreign_key => "logging_id"

    validates :access_log, presence: true
    validates :error_log, presence: true
    validates :log_level, :inclusion => {:in => [1, 2, 3, 4]}
    validates :log_archive, :inclusion => {:in => [nil, 0, 1]}
    validates :log_size, numericality: {only_integer: true}, if: lambda {|m| m.log_size.present?}

    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
      "access_log=#{access_log} error_log=#{error_log} log_level=#{log_level}"
    end
    def dumpXml(builder)
      builder.tag! 'logging' do |log|
        log.tag! 'accesslog', access_log
        log.tag! 'errorlog', error_log
        log.tag! 'playlistlog', playlist_log if !playlist_log.nil? && !playlist_log.empty?
        log.tag! 'logsize', log_size if log_size
        log.tag! 'logarchive', log_archive if log_archive
        log.tag! 'loglevel', log_level
      end
    end
  end
end