module JamRuby
  class OnlinePresence < ActiveRecord::Base

    PERMISSION_MSG = "You do not have permission to perform this operation."

    attr_accessible :player_id, :service_type, :username
    belongs_to :player, polymorphic: true

    validates :service_type, presence:true, length: {maximum: 100}
    validates :username, presence:true, length: {maximum: 100}

    validate :username_service_type_unique

    def username_service_type_unique
      match = OnlinePresence.exists?(:username => self.username, :service_type => self.service_type)
      raise ConflictError, "Username #{self.username} is already associated with a #{self.service_type} account" if match
    end

    def self.index(options = {})
      raise StateError, "The user is not specified." if options[:id].blank?
      OnlinePresence.where("player_id = ?", options[:id])
    end

    # Create with target_player (target_player is either user or band):
    def self.create(target_player, options = {}, save = true)
      auth_player(target_player, options)
      raise StateError, "Missing required information" if options[:service_type].blank? || options[:username].blank?
      
      up = OnlinePresence.new({
        :player_id => target_player.id, 
        :service_type => options[:service_type], 
        :username => options[:username]
      })

      up.save! if save
      up
    end

    def self.update(target_player, options = {})
      auth_player(target_player, options)
      raise StateError, "Missing required information" if options[:service_type].blank? || options[:username].blank? || options[:id].blank?

      up = OnlinePresence.find(options[:id])
      up.service_type = options[:service_type]
      up.username = options[:username]
      up.save!
    end

    def self.delete(target_player, options = {})
      id = options[:id]
      raise StateError, "Missing required information" if id.blank?
      online_presence = OnlinePresence.find(id)

      if online_presence.player_id != target_player.id
        raise JamPermissionError, PERMISSION_MSG
      end

      unless online_presence.nil?
        OnlinePresence.destroy(id)
      end
    end

    private
    def self.auth_player(target_player, options={})
      if target_player.nil? || options[:player_id] != target_player.id        
        raise JamPermissionError, PERMISSION_MSG 
      end
    end
  end
end