# This class hooks into Redmine's View Listeners in order to
# add content to the page
class PiwikHooks  < Redmine::Hook::ViewListener

# Adds the Piwik code to the layout if the current user meets
  # the conditions setup by the System Administrator
  def view_layouts_base_body_bottom(context = { })
    log_anon = Setting.plugin_piwik_plugin['piwik_log_anonymous']
    log_auth = Setting.plugin_piwik_plugin['piwik_log_authenticated']
    log_admin = Setting.plugin_piwik_plugin['piwik_log_administrator']
    log_url = Setting.plugin_piwik_plugin['piwik_log_url']
    log_id = Setting.plugin_piwik_plugin['piwik_log_id']

    if (!log_url.nil? && !log_id.nil?)

      if (context[:request].env['HTTPS'] == 'on')
        log_url = log_url.gsub(/http:|https:/, 'https:')
      else
        log_url = log_url.gsub(/http:|https:/, 'http:')
      end

      if (User.current.anonymous? && log_anon) || # Anon user
        (User.current.logged? && log_auth && !User.current.admin?) || # Auth users who are not admins
        (User.current.admin? && log_admin) # Admin user
       output = "<!-- Piwik -->
<script type=\"text/javascript\" src=\"#{log_url}piwik.js\"></script>
<script type=\"text/javascript\">
try {
var piwikTracker = Piwik.getTracker(\"#{log_url}piwik.php\", #{log_id});
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
} catch( err ) {}
</script><noscript><p><img src=\"#{log_url}piwik.php?idsite=#{log_id}\" style=\"border:0\" alt=\"\"/></p></noscript>
<!-- End Piwik Tag -->"
        return output
      else
        return ''
      end
    else
      return ''
   end
  end
end
