module JamRuby
  class Jamblaster < ActiveRecord::Base

    attr_accessible :user_id, :serial_no, :client_id, :user_ids, as: :admin


    belongs_to :user, class_name: 'JamRuby::User'
    has_many :jamblasters_users, class_name: "JamRuby::JamblasterUser"
    has_many :users, class_name: 'JamRuby::User', through: :jamblasters_users
    has_many :jamblaster_pairing_requests, class_name: "JamRuby::JamblasterPairingRequest", foreign_key: :jamblaster_id
    belongs_to :connection, class_name: "JamRuby::Connection", foreign_key: "client_id"

    validates :serial_no, uniqueness: true
    validates :client_id, uniqueness: true

    before_save :sanitize_active_admin

    def sanitize_active_admin
      self.client_id = nil if self.client_id == ''
      self.serial_no = nil if self.serial_no == ''
    end

    def most_recent_pairing
      jamblaster_pairing_requests.where(active: true).first
    end

    def self.bootstrap(serialno)
      jb = Jamblaster.find_by_serial_no(serialno)
      if jb
        return jb
      end

      jb = Jamblaster.new
      jb.serial_no = serialno
      jb.save
      jb
    end

    class << self

      @@mq_router = MQRouter.new
      @@message_factory = MessageFactory.new

      def send_pair_attempt(jbid, scid, vtoken)
        msg = @@message_factory.pair_attempt(
            jbid, scid, vtoken
        )

        @@mq_router.publish_to_client(jbid, msg, {:client_id => scid})
      end
    end
  end
end