module JamRuby
  class IcecastMountTemplate < ActiveRecord::Base

    attr_accessor   :hostname, :default_mime_type # used by jam-admin

    attr_accessible :authentication_id, :source_username, :source_pass, :max_listeners, :max_listener_duration,
                    :dump_file, :intro, :fallback_mount, :fallback_override, :fallback_when_full, :charset, :is_public,
                    :stream_name, :stream_description, :stream_url, :genre, :bitrate, :mime_type, :subtype, :burst_size,
                    :mp3_metadata_interval, :hidden, :on_connect, :on_disconnect, :name, as: :admin

    belongs_to  :authentication, class_name: "JamRuby::IcecastUserAuthentication", inverse_of: :mount, foreign_key: 'authentication_id'
    has_many    :mounts, class_name: "JamRuby::IcecastMount", inverse_of: :mount_template, foreign_key: 'icecast_mount_template_id'
    has_many    :servers, class_name: "JamRuby::IcecastServer", inverse_of: :mount_template, foreign_key: 'mount_template_id'

    validates :source_username, length: {minimum: 5}, if: lambda {|m| m.source_username.present?}
    validates :source_pass, length: {minimum: 5},  if: lambda {|m| m.source_pass.present?}
    validates :max_listeners, length: {in: 1..15000}, if: lambda {|m| m.max_listeners.present?}
    validates :max_listener_duration,  length: {in: 1..3600 * 48}, if: lambda {|m| m.max_listener_duration.present?}
    validates :fallback_override, :inclusion => {:in => [0, 1]} , if: lambda {|m| m.fallback_mount.present?}
    validates :fallback_when_full, :inclusion => {:in => [0, 1]} , if: lambda {|m| m.fallback_mount.present?}
    validates :is_public, presence: true, :inclusion => {:in => [-1, 0, 1]}
    validates :bitrate, numericality: {only_integer: true}, if: lambda {|m| m.bitrate.present?}
    validates :mime_type, presence: true
    validates :burst_size, numericality: {only_integer: true}, if: lambda {|m| m.burst_size.present?}
    validates :mp3_metadata_interval, numericality: {only_integer: true}, if: lambda {|m| m.mp3_metadata_interval.present?}
    validates :hidden, :inclusion => {:in => [0, 1]}

    before_save       :sanitize_active_admin
    after_save        :poke_config
    after_initialize  :after_initialize
    before_destroy    :poke_config

    def after_initialize # used by jam-admin
      self.hostname = 'localhost:3000'
      self.default_mime_type = 'mp3'
    end

    def poke_config
      servers.update_all(config_changed: 1)
    end

    def sanitize_active_admin
      self.authentication_id = nil if self.authentication_id == ''
    end

    # pick a server that's in the same group as the user that is under the least load
    def build_session_mount(music_session, active_music_session)
      mount = IcecastMount.new
      mount.authentication = authentication
      mount.mount_template = self
      mount.name = "/" + SecureRandom.urlsafe_base64 + (mime_type == 'audio/mpeg' ? '.mp3' : '.ogg')
      mount.music_session_id = music_session.id
      mount.source_username = 'source'
      mount.source_pass = APP_CONFIG.icecast_hardcoded_source_password || SecureRandom.urlsafe_base64
      mount.stream_name = "JamKazam music session created by #{music_session.creator.name}"
      mount.stream_description = music_session.description
      mount.stream_url = "https://www.jamkazam.com" ## TODO/XXX, the jamkazam url should be the page hosting the widget
      mount.genre = music_session.genre.description
      mount
    end
  end
end