module JamRuby
  class MachineFingerprint < ActiveRecord::Base

    @@log = Logging.logger[MachineFingerprint]

    belongs_to :user, :class_name => "JamRuby::User"
    belongs_to :jam_track_right, :class_name => "JamRuby::JamTrackRight"
    has_one :detail, :class_name => "JamRuby::MachineExtra"
    belongs_to :fingerprint_whitelist, class_name: 'JamRuby::FingerprintWhitelist', foreign_key: :fingerprint

    TAKEN_ON_SUCCESSFUL_DOWNLOAD = 'dl'
    TAKEN_ON_FRAUD_CONFLICT = 'fc'

    PRINT_TYPE_ALL = 'a'
    PRINT_TYPE_ACTIVE = 'r'


    validates :user, presence:true
    validates :when_taken, :inclusion => {:in => [TAKEN_ON_SUCCESSFUL_DOWNLOAD, TAKEN_ON_FRAUD_CONFLICT]}
    validates :fingerprint, presence: true
    validates :print_type, presence: true, :inclusion => {:in =>[PRINT_TYPE_ALL, PRINT_TYPE_ACTIVE]}
    validates :remote_ip, presence: true

    def self.create(fingerprint, user, when_taken, print_type, remote_ip, extra, jam_track_right = nil)
      mf = MachineFingerprint.new
      mf.fingerprint = fingerprint
      mf.user = user
      mf.when_taken = when_taken
      mf.print_type = print_type
      mf.remote_ip = remote_ip
      mf.jam_track_right = jam_track_right
      if mf.save
        MachineExtra.create(mf, extra) if extra
      else

        @@log.error("unable to create machine fingerprint: #{mf.errors.inspect}")
      end
      mf
    end

    def admin_url
      APP_CONFIG.admin_root_url + "/admin/machine_fingerprints/" + id
    end

    def to_s
      "#{fingerprint} #{remote_ip} #{user} #{detail}"
    end
  end
end