ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
require 'feed_validator/assertions'
require 'ftools'

#--######################################################################
# 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]

module Test::Unit::Assertions
  def assert_block(msg="") 
    _wrap_assertion do
      if (! yield)
        logger.debug("Failure: #{msg}")
        raise Test::Unit::AssertionFailedError.new(msg.to_s)
      end
    end
  end
end

class ActionController::Integration::Session
  def logger
    RAILS_DEFAULT_LOGGER
  end
end

class Test::Unit::TestCase
  # Turn off transactional fixtures if you're working with MyISAM tables in MySQL
  self.use_transactional_fixtures = true
  
  # Instantiated fixtures are slow, but give you @david where you otherwise would need people(:david)
  self.use_instantiated_fixtures  = false
  
  # Add more helper methods to be used by all tests here...
  def logger
    RAILS_DEFAULT_LOGGER
  end
  
  def login(who)
    logger.debug("Login: #{who.inspect}")
    open_session do |sess|
      logger.debug("Opening session")
      sess.post "login/login", :user => {:email => who.email, :password => who.password }
      assert_not_nil sess.assigns(:logged_in_user)
    end
  end
  
  # Method #create_some_data creates some test records for a page (Comment, Checkout, Upload, New Page)
  def create_some_data(p, u = @andy)
    for i in 0..15
      c= Comment.new(:text => "Text of comment #{i} by user tony", :user => u, :version => p.current_version, :page => p, :site => p.site)
      assert c.save
      co = Checkout.new(:user => u, :page => p, :site => p.site, :note => "Checkout #{i} by Andy")
      assert co.save
      co.checkin(u)
      upl = Upload.new(:filename => 'filename.html', :upload_type => 'Image', 
        :content_type => 'Content type', :description => 'Description of upload', 
        :user_id => u.id, :rel_path => 'x/y/z.html')
      assert upl.save
      new_page2, new_co2 = WikiPage.new_using_template(:presentation_name => 'New Page Using Another Page as a Template', :source_version => p.current_version, :user => u, :site => p.site)  
      assert_no_errors(new_page2)
      assert_no_errors(new_co2)
      new_co2.checkin(u)
    end
  end
  
  def assert_field(name)
    assert_tag :tag => "input", :attributes => {:id => name}
  end
  
  def assert_no_field(name)
    assert_no_tag :tag => "input", :attributes => {:id => name}
  end
  
  def assert_wiki_menu(wiki, page, html, action)
    result_expected = []
    result_expected << ["", '/' + wiki.rel_path + '/' + page.rel_path, "View"]
    result_expected << ["", "/#{wiki.site_folder}/#{page.id}/discussion", "Discussion"]
    result_expected << ["", "/#{wiki.site_folder}/#{page.id}/edit", "Edit"]
    result_expected << ["", "/#{wiki.site_folder}/#{page.id}/new", "New"]
    result_expected << ["", "/#{wiki.site_folder}/#{page.id}/info", "Info"]
    result_expected << ["", "/", "Home"]
    result_expected.each do |r|
      r[0] = " class=\"current\"" if r[2] == action
    end
    result = html.scan(/<a href="(.*?)".*?<span>(.*?)<\/span>/)    
    assert result_expected, result
    if action == 'edit'
      # TODO implement functional test for confirm message
    end
  end
  
  def assert_errors(object = nil)
    if object
      object.errors.full_messages.each do |message|
        assert_tag :content => message
      end
    else
      assert_tag error_message_field      
    end
  end
  
  def assert_no_errors(object = nil)
    if object
      object.errors.full_messages.each do |message|
        assert_no_tag :content => message 
      end
    else
      assert_no_tag error_message_field
    end
  end
  
  def assert_pattern(pat, html, result)
    html =~ pat
    assert_equal result, $&
  end
  
  def error_message_field
    {:tag => 'div', :attributes => { :class => 'errorExplanation', :id => 'errorExplanation' }}
  end
  
  def assert_save(object)
    if !object.save
      assert_equal '', object.errors.full_messages.join(", ")      
    end
  end
  
  def assert_enhanced_file(path)
    html = IO.readlines(path).join
    assert [true, true, true], [html.include?("<!-- epfwiki head start -->"), html.include?("onload"), html.include?("<!-- epfwiki head end -->")]
  end 
  
  def assert_version_file(path)
    html = IO.readlines(path).join
    logger.debug('html: ' + html)
    assert_equal [path, false,true, true], [path, html.include?('<!-- epfwiki head start -->'), html.include?('<body>'), html.include?("<div id=\"treebrowser_tag_placeholder\">")]
  end
  
  def assert_tologin
    #assert_equal  ::MSG_LOGIN, flash['notice']
    assert_equal @request.request_uri, session["return_to"]
    assert_redirected_to :controller => 'login'
  end
  def assert_unot_admin_message
    assert_equal LoginController::FLASH_UNOT_ADMIN, flash['error']
    assert_redirected_to :controller => "other", :action => "error"
  end
  def assert_unot_cadmin_message
    assert_equal LoginController::FLASH_UNOT_CADMIN, flash['error']
    assert_redirected_to :controller => "other", :action => "error"
  end
  
  def assert_illegal_get
    assert_redirected_to :controller => 'other', :action => 'error'
    assert ::FLASH_USE_POST_NOT_GET, flash['error']
  end
 
  def upload_file(path, content_type="application/octet-stream")
    file = Tempfile.new(File.basename(path))
    FileUtils.copy_file(path, file.path)
    (class << file; self; end;).class_eval do
      alias local_path path
      define_method(:original_filename) { File.basename(path)}
      define_method(:content_type) { content_type }
    end
    return file
  end
  
  def copyright_files(path)
    paths = Array.new
     (Dir.entries(path) - [".", ".."]).each do |entry| 
      new_path = File.expand_path(entry, path)
      if FileTest.directory?(new_path)   
        paths = paths + copyright_files(new_path)
      else
        if entry =~ /\.rb\z/i
          paths << new_path 
        end
      end
    end
    return paths
  end
end