

module Buildwise
  class App
    module ApiHelper



      
      def is_authenticated_for_project?(project, api_key)

        if api_key.nil? || project.nil? || project.config.nil? || project.config.api_key.nil? || project.config.api_key.strip.empty?
          return false
        end
        
        result = (project.config.api_key == api_key) rescue false
        return result
      end
      
      
      def is_authenticated_for_server?(api_key)

        if settings.server_api_key.nil? || settings.server_api_key.strip.empty?
          return false
        end
        
        result = (settings.server_api_key == api_key) rescue false
        return result
      end
      
      
      def create_project(project_hash)
        result = {}                      
        puts "[API] create_project: #{project_hash.inspect}"
        project_hash.transform_keys(&:to_s)
              
        project_dir = project_hash["project_dir"]
        if project_dir.nil? || !File.exist?(project_dir.strip) 
          result[:status] = "Failed"
          result[:message] = "Invalid project working dir: '#{project_dir}'"
          return result.to_json        
        end
        
        project_identifier = project_hash["identifier"]    
        project_name = project_hash["name"]
        if Project.where(:identifier=> project_identifier).first 

          result[:status] = "Failed"
          result[:message] = "The project '#{project_identifier}' already existed"
          return result.to_json    
        end
           

        options = {:application_name => project_identifier}        
        options[:builder] = {}
        if project_hash["rake_task"]
          options[:builder]["task"] = project_hash["rake_task"]
        elsif project_hash["ui_test_task"]
          options[:builder]["ui_test_task"] = project_hash["ui_test_task"]
        end
        
        if project_hash["load_test_task"]
          options[:builder]["load_test_task"] = project_hash["load_test_task"]
        end           
                
        options[:builder]["ui_test_framework"] = project_hash["ui_test_task_framework"] if project_hash["ui_test_task_framework"]
    		options[:scm] = { "user_name" => project_hash["scm_user"], "password" => project_hash["scm_pass"] } if project_hash["scm_user"]

        if project_hash[:project_template] && project_hash[:project_template] == "Ruby on Rails"
          options[:builder]["migrate_database_task"] = project_hash["migrate_database_task"] if project_hash["migrate_database_task"]
          options[:builder]["unit_test_task"] = project_hash["unit_test_task"] if project_hash["unit_test_task"]
        end

        options[:ui_tests] ||= {}
        options[:ui_tests]["test_dir"] = project_hash["ui_test_dir"] if project_hash["ui_test_dir"]
        options[:ui_tests]["report_dir"] = project_hash["ui_test_report_dir"] if project_hash["ui_test_report_dir"]

        project_dir.strip!

        scm = determine_scm(project_dir)
        if scm.nil?
          @error = "No supported SCM not found in #{project_dir}"
          redirect "/projects/new?error=#{@error}"
          return
        end

        command = BuildWise::AddCommand.new(project_dir, options)
        begin          
          command.run        
        rescue => e
          result[:status] = "Failed"
          result[:message] = "Failed to create project: #{e}"
          return result.to_json        
        end
        

        Project.load_projects_from_working_dir([project_identifier])  
    
        @project = Project.where(:identifier => project_identifier).first
        if project_hash["account_id"]
          @project.update_column(:account_id, project_hash["account_id"])
        end        
        @project.update_column(:name, project_name)

        project_config = @project.config
        project_config.environment_variables["BUILDWISE_MASTER"] ||= root_url
        project_config.environment_variables["DISTRIBUTED_MAX_BUILD_TIME"] ||= 3600
        project_config.environment_variables["DISTRIBUTED_BUILD_CHECK_INTERVAL"] ||= 15
    
        if project_hash["is_load_testing"] && project_hash["is_load_testing"].to_s == "true"
          project_config.is_parallel = true
          project_config.is_load_testing = true
      
          project_config.app_name = project_name rescue "AgileTravel-Load"
          project_config.agent_work_dir = project_dir
          project_config.load_max_iteration_count = project_hash[:load_max_iteration_count] if project_hash[:load_max_iteration_count]
          project_config.load_server_url =  project_hash[:load_server_url] if project_hash[:load_server_url]
          project_config.load_max_agent_count =  project_hash[:load_max_agent_count] if project_hash[:load_max_agent_count]
      

          special_mac_working_dir = File.expand_path("~/work/projects/agiletravel-ui-tests")
          if project_config.agent_work_dir == special_mac_working_dir|| project_config.agent_work_dir == "C:\\work\\agiletravel-ui-tests"
            project_config.agent_work_dir = "#{special_mac_working_dir};C:\\work\\agiletravel-ui-tests"
          end
        end
    
        project_config.save
        
        result[:project_id] = @project.id
        result[:project_identifier] = @project.identifier        
        result[:status] = "OK"
        result[:message] = "The project '#{@project.identifier}' created successfully"
        return result.to_json
      end
      
      
    end

    helpers ApiHelper
  end
end