class BuildStepExecution < ActiveRecord::Base

  belongs_to :build  
  before_save :set_duration
  
  def is_ui_test?
    self.task_name.downcase == "ui test" || self.task_name.downcase == "api test"
  end
  
  def set_duration
    if self.end_time && self.start_time
      self.duration = self.end_time - self.start_time
    end



  end
  
  def elapsed_time_in_progress
    (Time.now - self.start_time) rescue nil
  end
   
  def log_output
    if log_file.nil? || !File.exist?(log_file)
      puts "[INFO] No log file '#{log_file}' detected yet"
      return ""
    end


    the_output = contents_for_display(log_file)

    unless RUBY_VERSION =~ /1.8/
      the_output = the_output.force_encoding("UTF-8")
    end

    return the_output
  end
  
  def safe_set_output(step_output)
    if step_output && step_output.size > 1000
      self.output = step_output.truncate(600) + "\n...\n" + step_output.last(400)
    else
      self.output = step_output
    end
  end
  
  def contents_for_display(file)
    return '' unless file && File.file?(file) && File.readable?(file)
    file_size_kbytes = File.size(file) / 1024
    if file_size_kbytes < MAX_DISPLAY_LOG_KB
      File.read(file)
    else

      contents = File.read(file, 100 * 1024)
      contents = contents[0..100*1024] + "\n...\n" + contents[-100*1024..-1]
      response = "#{file} is #{file_size_kbytes} kbytes - too big to display in the dashboard, the output is truncated\n\n\n"
      response += contents
    end
  end
  
  
  def last_runs(number, max_id = nil)
    if max_id.nil?
      array = BuildStepExecution.joins(:build).where("builds.project_id = ? AND task_name = ?", self.build.project_id, self.task_name).order("ID desc").limit(number).to_a
    else
      array = BuildStepExecution.joins(:build).where("builds.project_id = ? AND task_name = ? AND id <= ?",  self.build.project_id, self.task_name, max_id).order("ID desc").limit(number).to_a      
    end  
    return array
  end
  
  def chart_data
    hash = {}
    hash["id"] = self.id
    hash["time"] = self.start_time.localtime.strftime("%Y-%m-%d %H:%M")
    hash["color"] = self.successful ? "#8BC34A" : "#ff6b68"    
    if self.duration
      hash["duration"] = self.pretty_duration rescue ""
      hash["y"] = self.duration.to_f ? self.duration.to_f : 0
    else
      hash["color"] = '#058DC7'
      hash["duration"] = self.pretty_duration(elapsed_time_in_progress) rescue ""
      hash["y"] = self.elapsed_time_in_progress ? self.elapsed_time_in_progress : 0
    end
    return hash
  end
  
  def pretty_duration(the_time = nil)
    the_time ||= self.duration
    parse_string = 
        if the_time < 60
            '%S sec'
        elsif the_time < 60 * 10            
          '%-M:%S'             
        elsif the_time < 3600
          '%M min'             
        else
          '%H h %M m'
        end

    Time.at(the_time).utc.strftime(parse_string)
  end

  def display_task_name    
    begin
      if self.task_name == "SCM Update"
        project_sources_dir = File.join(build.project.working_dir, "sources", ".git")
        return "Git Pull"
      end
    rescue 
    end
    
    return self.task_name
  end
  
  
end