require 'base64'

class Oauth < ActiveRecord::Base
  attr_accessible :client_id, :client_secret, :redirect_uri, :access_token,
                  :refresh_token, :token_created_at,:token_expires_in, :user_id

  belongs_to :user

  def gen_code
    code = Base64.urlsafe_encode64 Digest::MD5.hexdigest "#{Time.now}-#{Random.new_seed}"
    update_column(:code, code)
    code
  end

  def gen_token
    access_token = Digest::MD5.hexdigest "#{Time.now}-#{Random.new_seed}"
    refresh_token = Digest::MD5.hexdigest "#{Random.new_seed}-#{Time.now}-#{Random.new_seed}"

    self.update_attributes(access_token: access_token,
                           refresh_token: refresh_token,
                           token_created_at: Time.now.to_i,
                           token_expires_in: Time.now.to_i + 24*60*60,
                           )
  end


  def self.code_valid?(code)
    # 1. 是否存在
    oauth = Oauth.where(code: code).order("ID desc").first
    return false unless oauth

    # 2. 是否超过10分钟
    return false  if Time.now.to_i - oauth.created_at.to_i > 10*60

    # 3. 是否有使用过
    return false if oauth.access_token.present?

    return true
  end


  def self.auth_code(code, client_id, client_secret)
    Oauth.where(code: code, client_id: client_id, client_secret: client_secret).order('id desc').first
  end

  def self.auth(access_token)
    oauth = self.find_by_access_token(access_token)
    return nil unless oauth
    oauth.user
  end


end