require 'base64'
require 'js_connect'

class VanillaForumsController < ApplicationController

  def log
    @log || Logging.logger[VanillaForumsController  ]
  end

  # displays the embedded forum
  # see http://vanillaforums.com/blog/jsconnect-technical-documentation-for-embedded-sso/
  def show

    user = {name: '', photourl: ''}
    if current_user
      name = current_user.admin ? "#{current_user.name} #{Rails.application.config.vanilla_staff_postfix}" : current_user.name
      user = {email: current_user.email, name: name,
              photourl: current_user.profile_pic,
              uniqueid: current_user.username}
    end
    user.merge!({client_id: Rails.application.config.vanilla_client_id})

    # json encode the user
    json = ActiveSupport::JSON.encode(user);
    # base 64 encode the user json
    signature_string = Base64.strict_encode64(json)
    # Sign the signature string with current timestamp using hmac sha1
    signature = Digest::HMAC.hexdigest(signature_string + ' ' +
                                           Time.now.to_i.to_s, Rails.application.config.vanilla_secret, Digest::SHA1)
    # build the final sso string
    @vanilla_sso = "#{signature_string} #{signature} #{Time.now.to_i} hmacsha1"

  end

  # callback for vanilla authentication
  # see http://vanillaforums.com/blog/jsconnect-technical-documentation
  # ruby jsconnect client library: https://github.com/vanillaforums/jsConnectRuby
  def authenticate

    user = {}
    if current_user

      name = current_user.admin ? "#{current_user.name} #{Rails.application.config.vanilla_staff_postfix}" : current_user.name
      user = {'email' => current_user.email, 'name' => name,
              'photourl' =>  current_user.resolved_photo_url,
              'uniqueid' =>  current_user.id}

      log.debug("user is logged in: #{user}")
    else
      log.debug("user is not logged in")
    end


    render :json => JsConnect::getJsConnectString(user, request,
                                                  Rails.application.config.vanilla_client_id, Rails.application.config.vanilla_secret), :content_type => 'application/javascript'

  end

  # only for testing; routes are conditionally based on test ENV
  def fake_root
    render layout: 'web'
  end
  # only for testing; routes are conditionally based on test ENV
  def fake_jsconnect
    render layout: 'web'
  end
end