require 'json'

class SpecBehaviour

  attr_accessor :name
  attr_accessor :start_line, :end_line
  attr_accessor :spec_context
  attr_accessor :wildcards

  def initialize(name, spec_file = nil)
    parse_rspec_behaviour_name(name)
    @spec_file = spec_file
  end







  def parse_rspec_behaviour_name(a_name)
    begin
      a_name.strip!
      

      ruby_hash_text = '{ "name":' + a_name   + '}' 

      ruby_hash_text.gsub!(/([{,]\s*):([^>\s]+)\s*=>/, '\1"\2"=>')


      ruby_hash_text.gsub!(/([{,]\s*)([0-9]+\.?[0-9]*)\s*=>/, '\1"\2"=>')


      ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>\s*:([^,}\s]+\s*)/, '\1\2=>"\3"')


      ruby_hash_text.gsub!(/([\[,]\s*):([^,\]\s]+)/, '\1"\2"')


      ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>/, '\1\2:')

      json_obj =  JSON.parse(ruby_hash_text)
      

      @name = json_obj["name"]
      @wildcards =  json_obj["wildcards"].split(",") rescue []   
    rescue => e
      puts("\n[ERROR] Failed to parse name, set to default, :#{e}")
      @wildcards = []
      @name = a_name
    end    
  end

  def display_name
    $MAX_BEHAVIOUR_NAME_DISPLAYED ||= 36


    @name.length > $MAX_BEHAVIOUR_NAME_DISPLAYED ? @name.strip[0,$MAX_BEHAVIOUR_NAME_DISPLAYED + 1] + "..." : @name
  end

  def source
    @code = spec_file.lines[(start_line-1)..(end_line-1)].join("\n")
  end

  def spec_file
    @spec_context.spec_file rescue nil
  end

  def lines
    source ? source.split("\n") : []
  end

  def file_path
		if @spec_file.local_work_path then
			@spec_file.local_work_path
		elsif ENV['TESTWISE_PROJECT_DIR'] then
			ENV['TESTWISE_PROJECT_DIR'] + "/" + File.basename(@spec_context.file_path)
		else
    	@spec_context.file_path
		end
  end

  def is_web_test?
    spec_file.is_web_test?
  end


  def wildcard_option(wildcard_key)
    require 'json'
    wildcard_config_json = File.join(File.dirname(file_path), "wildcard-config.json");
    if File.exist?(wildcard_config_json) 
      the_data_options = JSON.parse(File.read(wildcard_config_json))[wildcard_key] rescue nil
      return the_data_options
    else
      return nil
    end
    
  end
  
end