module JamRuby
  class UserAuthorization < ActiveRecord::Base

    attr_accessible :provider, :uid, :token, :token_expiration, :secret, :user, :refresh_token

    self.table_name = "user_authorizations"

    self.primary_key = 'id'

    belongs_to :user, :class_name => "JamRuby::User", :foreign_key => "user_id"
    validates :provider, :uid, :user, :presence => true
    validates_uniqueness_of :uid, scope: :provider
    # token, secret, token_expiration can be missing

    def is_active?
      token_expiration && token_expiration < Time.now
    end

    def self.refreshing_google_auth(user)
      auth = self.where(:user_id => user.id)
          .where(:provider => 'google_login')
          .limit(1).first

      # if we have an auth that will expire in less than 10 minutes
      if auth && auth.refresh_token && auth.token_expiration < Time.now - 60 * 10

        begin
          oauth_client = OAuth2::Client.new(
              Rails.application.config.google_client_id, Rails.application.config.google_secret,
              :site => "https://accounts.google.com",
              :token_url => "/o/oauth2/token",
              :authorize_url => "/o/oauth2/auth")
          access_token = OAuth2::AccessToken.from_hash(oauth_client, {:refresh_token => auth.refresh_token})
          access_token = access_token.refresh!

          auth.token = access_token.token
          auth.token_expiration = Time.now + access_token.expires_in
          auth.save
          return auth
        rescue Exception => e
          puts "could not refresh; #{e}"
          if auth
            auth.destroy
          end
          # couldn't refresh; probably the user has revoked the app's rights
          return nil
        end
      else
        auth
      end
    end

    def self.google_auth(user)
      self
        .where(:user_id => user.id)
        .where(:provider => 'google_login')
        .where(['token_expiration IS NULL OR (token_expiration > ? OR refresh_token is not null)', Time.now])
        .limit(1)
    end

  end
end
