class TestCase < ActiveRecord::Base
  belongs_to :test_file, counter_cache: true

  MAX_FAILURE_SIZE = 10240

  attr_accessor :start_line
  attr_accessor :end_line

  validates :name, uniqueness: { scope: :test_file_id, message: "should not duplicate within a test script file", case_sensitive: true }  


  before_create :normalize_name
  
  before_save :normalize_data
  after_save :update_test_file
  
  def source
    test_file.lines[start_line..(end_line || -1)].join("\n") rescue ""
  end

  def spec_behaviour
    begin
      spec_file = SpecFile.new(test_file.file_path, test_file.lines)
      spec_file.behaviour_lookups[name] rescue nil
    rescue => e
      return nil
    end
  end
  


  def remove_prefix(prefix)
    test_case_name = self.name
    if test_case_name.start_with?(prefix)
      self.name = test_case_name.sub(prefix, "")
      self.name.strip!
    end
  end

  def safe_duration
    if self.test_file && self.test_file.build && self.test_file.build.test_syntax_framework == "JUnit"
       sprintf('%.3f', self.duration)
    else
      sprintf('%.2f', self.duration)
    end    
  end


  private

  def normalize_name


    if self.test_file && self.test_file.build 
      
      if self.test_file.build.project.config.remove_suite_name_from_test_case
        begin
          suite_name = self.test_file.description
          if suite_name && suite_name.strip.size >= 3

            remove_prefix(suite_name)
          end
        
        rescue => e
          puts "[WARN] failed to remove suite-name, continue. #{e}"
        end      
      end
            
    end
    
  end
  

  def normalize_data  
    begin
      if self.failure && self.failure.size > MAX_FAILURE_SIZE
        self.failure = self.failure[-MAX_FAILURE_SIZE..-1]
      end
    rescue => e
      puts("failed to normalize data #{e}")
    end
  end
  
  
  def update_test_file
    if self.test_file
      self.test_file.recalc
      self.test_file.save
    end
  end

end