module JamRuby
  class IcecastUserAuthentication < ActiveRecord::Base

    attr_accessible :authentication_type, :filename, :allow_duplicate_users, :mount_add, :mount_remove, :listener_add,
                    :listener_remove, :unused_username, :unused_pass, :auth_header, :timelimit_header,  as: :admin

    has_one :mount, class_name: 'JamRuby::IcecastMount', inverse_of: :authentication, :foreign_key => 'authentication_id'

    validates :authentication_type, presence: true, :inclusion => {:in => ["url", "htpasswd"]}
    validates :allow_duplicate_users, :inclusion => {:in => [0, 1]}, if: :htpasswd_auth?
    validates :unused_username, length: {minimum: 5}, if: :url_auth_and_user_present?
    validates :unused_pass, length: {minimum: 5}, if: :url_auth_and_pass_present?
    validates :mount_add, presence: true, if: :url_auth?
    validates :mount_remove, presence: true, if: :url_auth?
    validates :listener_add, presence: true, if: :url_auth?
    validates :listener_remove, presence: true, if: :url_auth?
    validates :auth_header, presence: true, if: :url_auth?
    validates :timelimit_header, presence: true, if: :url_auth?

    before_destroy :poke_config
    after_save :poke_config

    def poke_config
      mount.server.update_attribute(:config_changed, 1) if mount && mount.server
    end

    def to_s
      "mount=#{mount} username=#{unused_username} auth_header=#{auth_header} timelimit_header=#{timelimit_header}"
    end

    def dumpXml (builder)
      builder.tag! 'authentication', type: authentication_type do |auth|
        auth.tag! 'option', name: 'mount_add', value: mount_add if !mount_add.nil? && !mount_remove.empty?
        auth.tag! 'option', name: 'mount_remove', value: mount_remove if !mount_remove.nil? && !mount_remove.empty?
        auth.tag! 'option', name: 'username', value: unused_username if !unused_username.nil? && !unused_username.empty?
        auth.tag! 'option', name: 'password', value: unused_pass if !unused_pass.nil? && !unused_pass.empty?
        auth.tag! 'option', name: 'listener_add', value: listener_add if !listener_add.nil? && !listener_add.empty?
        auth.tag! 'option', name: 'listener_remove', value: listener_remove if !listener_remove.nil? && !listener_remove.empty?
        auth.tag! 'option', name: 'auth_header', value: auth_header if !auth_header.nil? && !auth_header.empty?
        auth.tag! 'option', name: 'timelimit_header', value: timelimit_header if !timelimit_header.nil? && !timelimit_header.empty?
      end
    end

    def htpasswd_auth?
      authentication_type == 'htpasswd'
    end

    def url_auth?
      authentication_type == 'url'
    end

    def url_auth_and_user_present?
      url_auth? && self.unused_username.present?
    end

    def url_auth_and_pass_present?
      url_auth? && self.unused_pass.present?
    end

  end
end