require 'openssl'
require 'digest/sha1'
require 'base64'
require 'cgi'
require 'time'
require 'json'

module JamRuby

  # Most of the code below was taken from the example located here:
  # https://github.com/assistly/multipass-examples/blob/master/ruby.rb
  class DeskMultipass

    API_KEY = "453ddfc0bab00130a9c13bc9a68cf24c"
    SITE_KEY = "jamkazam"
    
    def initialize(user)
      @user = user
      generate_token_and_signature
    end

    def token
      @token
    end

    def signature
      @signature
    end

    private
      def generate_token_and_signature
        key = Digest::SHA1.digest(API_KEY + SITE_KEY)[0...16]

        # Generate a random 16 byte IV
        iv = OpenSSL::Random.random_bytes(16)

        json = JSON.generate(
                :uid => @user.id,
                :expires => (Time.now + 300).iso8601,
                :customer_name => @user.name,
                :customer_email => @user.email)

        cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
        cipher.encrypt
        cipher.key = key
        cipher.iv = iv
        encrypted = cipher.update(json) + cipher.final

        prepended = iv + encrypted
        token = Base64.encode64(prepended)
        signature = Base64.encode64(OpenSSL::HMAC.digest('sha1', API_KEY, token))

        @token = CGI.escape(token)
        @signature = CGI.escape(signature)
      end
  end
end