# More information:
# * {EPF Wiki Data model}[link:files/doc/DATAMODEL.html]
#--######################################################################
# Copyright (c) 2006 Logica
# 
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# 
# Onno van der Straaten:: initial implementation
#++######################################################################
# {Copyright (c) 2006 Logica}[link:files/COPYRIGHT.html]

class Notifier < ActionMailer::Base
  
  def welcome_pw_confirmationlink(user, request_host = ENV['EPFWIKI_HOST'])
    content_type "text/html"
    @recipients = user.email
    @from = ENV['EPFWIKI_REPLY_ADDRESS']
    @subject =  "[" + ENV['EPFWIKI_APP_NAME'] + "] Welcome" 
    @body['user'] = user
    @body['admin'] = User.find_central_admin
    @body['subject'] = @subject
    @body['request_host'] = request_host
  end
  
  
  def lost_password(user, urls)
    content_type "text/html"
    @recipients = user.email
    @from = ENV['EPFWIKI_REPLY_ADDRESS']
    @subject = "[" + ENV['EPFWIKI_APP_NAME'] + "] New Password"
    @body['user'] = user
    @body['admin'] = User.find_central_admin
    @body['cnt'] = User.count
    @body['urls'] = urls
  end

  def error_report(exception, trace, session, params, env, sent_on = Time.now)
    content_type "text/html" 
    @recipients         = User.find_central_admin.email
    @from               = ENV['EPFWIKI_REPLY_ADDRESS']
    @subject            = "[Error] exception in #{env['REQUEST_URI']}" 
    @sent_on            = sent_on
    @body["exception"]  = exception
    @body["trace"]      = trace
    @body["session"]    = session
    @body["params"]     = params
    @body["env"]        = env
  end
  
  def summary(params, runtime = Time.now)
    content_type "text/html" 
    
    case params[:type]
    when 'D' # daily
      starttime = (runtime - 1.day).at_beginning_of_day
      endtime = runtime.at_beginning_of_day
      @bcc = email_addresses_4_report(User.find_all_by_notify_daily(1))
      subject_text = 'Daily'
    when 'W' # weekly
      starttime = (runtime - 1.week).at_beginning_of_week
      endtime = runtime.at_beginning_of_week
      @bcc = email_addresses_4_report(User.find_all_by_notify_weekly(1))
      subject_text = 'Weekly'
    when 'M' # monthly
      starttime = (runtime - 1.month).at_beginning_of_month
      endtime = runtime.at_beginning_of_month
      @bcc = email_addresses_4_report(User.find_all_by_notify_monthly(1))
      subject_text = 'Monthly'
    else
      raise 'Report type is required'
    end
    
    @bcc = email_addresses_4_report(params[:user]) unless params[:user].blank?
    @subject = "[#{ENV['EPFWIKI_APP_NAME']}] #{subject_text} Summary" 

    items = UserVersion.find(:all, :conditions => ['created_on > ? and created_on < ?', starttime, endtime ]) +
    Comment.find(:all, :conditions => ['created_on > ? and created_on < ?', starttime, endtime ]) +
    Upload.find(:all, :conditions => ['created_on > ? and created_on < ?', starttime, endtime ]) +
    Wiki.find(:all, :conditions => ['created_on > ? and created_on < ?', starttime, endtime ])+
    Update.find(:all, :conditions => ['created_on > ? and created_on < ?', starttime, endtime ]) +
    User.find(:all, :conditions => ['created_on > ? and created_on < ?', starttime, endtime ]) +
    WikiPage.find(:all, :conditions => ['created_on > ? and created_on < ? and tool=?', starttime, endtime, 'Wiki'])
    Checkout.find(:all)
    items.sort_by {|item|item.created_on}
    @body['wikis'] = []
    items.each do |item|
      logger.debug("item: #{item.inspect}")
      w = nil
      case item.class.name
      when Comment.name then w = item.site
      when Wiki.name then w = item
      when Update.name then w = item.wiki
      when Checkout.name then w = item.site
      when Version.name then w = item.wiki
      end
      @body['wikis'] << w if !w.nil?
    end
    @body['wikis'] = @body['wikis'].uniq    
    @from               = ENV['EPFWIKI_REPLY_ADDRESS']
    @sent_on            = Time.now
    @body['runtime']    = runtime
    @body['endtime']    = endtime
    @body['starttime']  = starttime
    @body['contributions']   = items
    @body['subject']    = subject
    @body['admin']      = User.find_central_admin
    @body['host']       = ENV['EPFWIKI_HOST']
    @body['items'] = items
  end 
  
  def env_to(user, session, params, env, sent_on = Time.now)
    content_type "text/html" 
    @recipients         = user.email
    @from               = ENV['EPFWIKI_REPLY_ADDRESS']
    @subject            = "[" + ENV['EPFWIKI_APP_NAME'] + "] " + params[:action]
    @sent_on            = sent_on
    @body["session"]    = session
    @body["params"]     = params
    @body["env"]        = env
  end
  
  def site_status(update, subject)
    content_type "text/html" 
    @from = ENV['EPFWIKI_REPLY_ADDRESS']
    @body['admin'] = User.find_central_admin
    @subject =  "[#{ENV['EPFWIKI_APP_NAME']}] #{subject}"
    @body['subject'] = @subject
    @recipients = update.user.email
    @cc = @body['admin'].email
    @body['update'] = update
  end
  
  def notification(theUsers, subject, introduction, text, request_host = ENV['EPFWIKI_HOST'])
    @from = ENV['EPFWIKI_REPLY_ADDRESS']
    content_type "text/html" 
    @subject = "[#{ENV['EPFWIKI_APP_NAME']}] #{subject}" 
    @bcc = email_addresses_4_report(theUsers)
    @body['link'] = "<a href=\"http://#{request_host}/users/account\">#{ENV['EPFWIKI_APP_NAME']}</a>"
    @body['introduction'] = introduction
    @body['text'] = text
    @body['admin'] = User.find_central_admin
    @body['subject'] = @subject
  end
  
  # TODO replace with notification
  def email(theUsers, theSubject, theFilePaths, theText, cc = nil)
    @from = ENV['EPFWIKI_REPLY_ADDRESS']
    @cc = email_addresses_4_report(cc) unless cc.nil?
    content_type "text/html" 
    @subject = "[" + ENV['EPFWIKI_APP_NAME'] + "] " + theSubject
    @recipients = email_addresses_4_report(theUsers)
    @body['text'] = theText
    @body['admin'] = User.find_central_admin
    for filePath  in theFilePaths
      attachment :content_type => "application/zip",   :body => File.open(filePath, "rb") {|io| io.read}, :filename => filePath.split("/").last
    end
  end
  
  def contributions_processed(user, contributions)
    # TODO remove
    #conditions = ['done=? and review_note_send_on is null and user_id=?', 'Y', user.id]
    #contributions = Upload.find(:all, :conditions => conditions) + Comment.find(:all, :conditions => conditions) + Version.find(:all, :conditions => ['done=? and review_note_send_on is null and baseline_process_id is null and user_id=?', 'Y', user.id])
    @recipients = email_addresses_4_report(user)
    #@cc = email_addresses_4_report(contributions.collect{|c|c.user}.uniq)
    content_type "text/html" 
    @body['contributions'] = contributions
    @body['admin'] = User.find_central_admin
    @body['user'] = user
    @bcc = email_addresses_4_report(@body['admin'])
    @subject = "[#{ENV['EPFWIKI_APP_NAME']}] Your contribution has been processed"
    @body['subject'] = @subject
  end
  
  def authorisation_problem(user, session, params, env)
    user = User.new(:name => 'Unknown', :email => 'Unknown') if user.nil?
    content_type 'text/html' 
    @body['admin']     = User.find_central_admin 
    @recipients         = @body['admin']
    @from               = ENV['EPFWIKI_REPLY_ADDRESS']
    @subject            = "[#{ENV['EPFWIKI_APP_NAME']}] Autorisation Problem Detected"
    @body['session']    = session
    @body['params']     = params
    @body['env']        = env
    @body['subject']    = @subject
    @body['user']       = user
  end
  
  def feedback(feedback)
    content_type 'text/html' 
    @body['admin']     = User.find_central_admin 
    @recipients         = @body['admin']
    @from               = ENV['EPFWIKI_REPLY_ADDRESS']
    @subject            = "[#{ENV['EPFWIKI_APP_NAME']}] Feedback Posted"
    @body['subject']    = @subject
    @body['feedback']   = feedback
    @body['anywiki']    = Wiki.find(:first, :conditions => ['obsolete_on is null'])
  end

end
