require File.join(File.dirname(__FILE__), "..", "utils", "command_line.rb")

module BuildWise
  class BuildStep

    attr_accessor :name # Database Migration
    attr_accessor :builder # Rake
    attr_accessor :task # test:units
    attr_accessor :enabled  
    attr_accessor :order
    
    attr_accessor :attributes  
    attr_accessor :config
    
    def initialize(name)
      self.name = name
      self.attributes = {}
    end
  
    def self.new_from_hash(hash = {})
      new_step = self.new(hash["name"])
      new_step.builder = hash["builder"]    
      new_step.enabled = hash["enabled"].to_s == "true" rescue false
      new_step.task = hash["task"]
      new_step.order = hash["order"]
      
      hash.delete("name")
      hash.delete("builder")
      hash.delete("order")
      hash.delete("enabled")
      hash.delete("task")    
      
      new_step.attributes = hash

      if hash["ui_test_framework"] && !hash["test_syntax_framework"]
        hash["test_syntax_framework"] = hash["ui_test_framework"] 
      end      
      return new_step
    end
  
    def add_attribute(name, value)
      self.attributes[name] = value
    end
  
    def get_attribute(name)
      self.attributes[name]
    end 
  
    def identifier
      self.name.gsub(" ", "").underscore
    end
    
    def is_test_execution_step?
      self.attributes["test_syntax_framework"] || self.attributes["ui_test_framework"] || identifier =="ui_test"
    end
    
  
    def is_valid?
      self.task && !self.task.empty?
    end

    def execute(config)
      the_builder = ::BuildWise::Builder.get(builder).new(config)
      the_builder.run(self.task)
      @successful = the_builder.successful?
      @output = the_builder.output
    end

    def successful?
      @successful
    end

    def output
      @output
    end

    def to_hash
      hash = self.attributes.dup
      hash[:name] = self.name
      hash[:enabled] = self.enabled
      hash[:order] = self.order
      hash[:task] = self.task
      hash[:builder] = self.builder
      return hash
    end


    def elapsed_time_in_progress
      Time.now - start_time rescue nil  
    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
      
    
  end

end