module JamRuby
  class IcecastTemplate < ActiveRecord::Base

    attr_accessible :limit_id, :admin_auth_id, :directory_id, :master_relay_id, :path_id, :logging_id,
                    :security_id, :name, :location, :admin_email, :fileserve, as: :admin

    belongs_to :limit, :class_name => "JamRuby::IcecastLimit", foreign_key: 'limit_id', :inverse_of => :templates
    belongs_to :admin_auth, :class_name => "JamRuby::IcecastAdminAuthentication", foreign_key: 'admin_auth_id', :inverse_of => :templates
    belongs_to :directory, :class_name => "JamRuby::IcecastDirectory", foreign_key: 'directory_id', :inverse_of => :templates
    belongs_to :master_relay,  :class_name => "JamRuby::IcecastMasterServerRelay", foreign_key: 'master_relay_id', :inverse_of => :templates
    belongs_to :path, :class_name => "JamRuby::IcecastPath", foreign_key: 'path_id', :inverse_of => :templates
    belongs_to :logging, :class_name => "JamRuby::IcecastLogging", foreign_key: 'logging_id', :inverse_of => :templates
    belongs_to :security, :class_name => "JamRuby::IcecastSecurity", foreign_key: 'security_id', :inverse_of => :templates

    has_many :servers, :class_name => "JamRuby::IcecastServer", :inverse_of => :template, :foreign_key => "template_id"

    #has_many :server_mounts, class_name: "JamRuby::IcecastServerMount", :inverse_of => :mount, :foreign_key
    #has_many :mounts, class_name: "JamRuby::IcecastMount", through: :server_mounts, :source => :template

    has_many :listen_socket_templates, :class_name => "JamRuby::IcecastTemplateSocket", :inverse_of => :template, :foreign_key => 'icecast_template_id'
    has_many :listen_sockets, :class_name => "JamRuby::IcecastListenSocket", :through => :listen_socket_templates  , :source => :socket

    validates :name, presence: true
    validates :location, presence: true
    validates :admin_email, presence: true
    validates :fileserve, :inclusion => {:in => [0, 1]}

    validates :limit, presence: true
    validates :admin_auth, presence: true
    validates :path, presence: true
    validates :logging, presence: true
    validates :security, presence: true
    validates :listen_sockets, length: {minimum: 1}

    before_save :sanitize_active_admin
    after_save      :poke_config
    before_destroy  :poke_config

    def poke_config
      servers.update_all(config_changed: 1)
    end

    def sanitize_active_admin
      self.limit_id = nil if self.limit_id == ''
      self.admin_auth_id = nil if self.admin_auth_id == ''
      self.directory_id = nil if self.directory_id == ''
      self.master_relay_id = nil if self.master_relay_id == ''
      self.path_id = nil if self.path_id == ''
      self.logging_id = nil if self.logging_id == ''
      self.security_id = nil if self.security_id == ''
    end
  end
end