
require 'digest/sha1'
require 'logger' 
require 'cgi'

module Utils # Need this, otherwise Rails won't load

  EPFWIKI_CSDIFF_PATH = "\"" + File.expand_path(Rails.root.to_s) + "/script/other/CSDiff/CSDiff.exe\""
  FLASH_RECORD_UPDATED = "Record updated!"
  FLASH_RECORD_CREATED = "Record created!"
  FLASH_RECORD_DELETED = "Record deleted!"
  FLASH_USE_POST_NOT_GET = 'The action does not allow a GET request, a POST request should be used'
  FLASH_NOT_OWNER = "This record was created by someone else, it can only be modified by the user that created it."
  
  MSG_EMAIL_SERVER_GENERATED = "**This message was generated by a server. Don't reply to this address.**"
  TIME_FORMAT = "%H:%M %d %b %Y"
  
  REMOVE_PATTERN1 = /<script([^\<])*(ContentPageResource|ContentPageSection|ContentPageToolbar|contentPage\.preload|contentPage\.js|ContentPageSubSection|steps\.js|backPath =)([^\<])*<\/script>/mi
 
  def self.notify_cadmin
    Notifier.env_to(User.find_central_admin, session.instance_variable_get("@data"), params, request.env, nil).deliver
  end
  
  def self.wrap_text(txt, col = 80)
    txt.gsub(/(.{1,#{col}})( +|$\n?)|(.{1,#{col}})/,
      "\\1\\3\n") 
  end
  
  def self.buildid(time)
    return time.strftime("%Y%m%d_%H%M")
  end
  
  def self.valid_filename(filename)
    filename.downcase.delete("&+-.\"/\[]:;=,\\").tr(' ','_')
  end
  
  def self.email_addresses_4_report(users)
    if  users.class.to_s == "User"
      return users.email
    else
      recipients = Array.new
      for user in users
        recipients = user.email if !recipients
        recipients << user.email
      end
      return recipients
    end
  end
  
  def self.db_script_version(path2migratefolder)
    files = Dir.entries(path2migratefolder)  - [".", ".."]
    version = 0
    files.each { |file| version = file.split("_")[0].to_i if file.split("_")[0].to_i > version } 
    return version
  end
  
  def self.write_log(logfilename, content)
    aOutputFile = File.new("#{ENV['EPFWIKI_ROOT_DIR']}log/#{logfilename}", "w")
    aOutputFile.puts(content)
    aOutputFile.close       
  end
  
  def self.hash_pw(pw)
    return Digest::SHA1.hexdigest(pw || '') 
  end

  
end
