Buildwise::App.controllers :admin do
  
  get "/settings" do
    authenticate_admin!    
    @local_gems = local_gems()
    render  "/admin/settings"
  end

  post "/settings" do    
    authenticate_admin!
    
    new_settings ||= {}
    new_settings[:builder_ruby_path] = params[:builder_ruby_path] # the ruby can be different from the ruby instance which starts BuildWise, but both need Sequel, Sinatra, Sinatra-r18n installed
    new_settings[:company_name] = params[:company_name]
    new_settings[:locale] = params[:locale]

    new_settings[:testwise_integration] =  params[:testwise_integration] && params[:testwise_integration] == "on"
    new_settings[:max_test_file_history] = params[:max_test_file_history].to_i if params[:max_test_file_history] && params[:max_test_file_history].strip.size > 0
    if new_settings[:max_test_file_history].nil? || new_settings[:max_test_file_history].to_i == 0
      new_settings[:max_test_file_history] = 10
    end

new_settings[:num_projects_per_page] = params[:num_projects_per_page].to_i if params[:num_projects_per_page] && params[:num_projects_per_page].strip.size > 0
if new_settings[:num_projects_per_page].nil? || new_settings[:num_projects_per_page].to_i == 0
  new_settings[:num_projects_per_page] = 5
end

    new_settings[:chart_height] = params[:chart_height].to_i if params[:chart_height] && params[:chart_height].strip.size > 0
    if new_settings[:chart_height].nil? || new_settings[:chart_height].to_i == 0
      new_settings[:chart_height] = 480
    end
    
    new_settings[:dynamic_chart_refresh_interval] = params[:dynamic_chart_refresh_interval].to_i if params[:dynamic_chart_refresh_interval] && params[:dynamic_chart_refresh_interval].strip.size > 0
    if new_settings[:dynamic_chart_refresh_interval].nil? || new_settings[:dynamic_chart_refresh_interval].to_i == 0
      new_settings[:dynamic_chart_refresh_interval] = 5000
    end
    
    settings.company_name = new_settings[:company_name] if new_settings[:company_name]
    settings.locale = new_settings[:locale].to_sym if new_settings[:locale]
    settings.testwise_integration = new_settings[:testwise_integration] 
    settings.max_test_file_history = new_settings[:max_test_file_history] if new_settings[:max_test_file_history]
    settings.num_projects_per_page = new_settings[:num_projects_per_page] 
    settings.chart_height = new_settings[:chart_height] if new_settings[:chart_height]
    settings.hide_test_script_content = new_settings[:hide_test_script_content] if new_settings[:hide_test_script_content]

    settings.dynamic_chart_refresh_interval = new_settings[:dynamic_chart_refresh_interval] if new_settings[:dynamic_chart_refresh_interval]
    
    new_settings[:show_execution_monitor_status] = params[:show_execution_monitor_status] && params[:show_execution_monitor_status] == 'on'

    settings.server_api_key = new_settings["server_api_key"] = params[:server_api_key] if params[:server_api_key]

    global_settings_file = File.join(BUILDWISE_HOME,"setting.yml")
    new_content = new_settings.to_yaml
    new_content.gsub!("!map:ActiveSupport::HashWithIndifferentAccess", "")
    File.open(global_settings_file, 'w') { |f| f.write(new_content) }
    
    Buildwise::App.cache.clear    
    redirect "/"
  end


  get "/gems", :cache => true,  :provides => [:js] do
    expires 60 * 60 # expire cached version at least every 1 hour
    my_local_gems = local_gems()
    @gem_list =  my_local_gems.map{ |name, specs|
      [
        name,
        specs.map{ |spec| spec.version.to_s }.join(',')
      ].join(' ')
    }
    erb "/admin/gems.js".to_sym, :layout => false
  end

  get "/suspend_project/:id" do
    authenticate_admin!

    @project = find_project(params[:id])
    @project.active = false
    @project.save
    erb "/admin/suspend_project.js".to_sym, :layout => false
  end

  get "/activate_project/:id" do
    authenticate_admin!
    @project = find_project(params[:id])
    @project.active = true
    @project.save
    erb "/admin/activate_project.js".to_sym, :layout => false
  end

  get "/delete_project/:id", :provides => [:js] do
    authenticate_admin!
    @project = find_project(params[:id])
    @project.destroy


    project_config_xml_file = @project.config_file_path
    File.delete(project_config_xml_file) if File.exist?(project_config_xml_file)

    project_working_dir = @project.working_dir
    if File.exist?(project_working_dir)
      FileUtils.rm_rf(project_working_dir)
    end

    render "/admin/delete_project.js".to_sym, :layout => false
  end

  get "/hide_project_for_public/:id", :provides => [:js] do
    authenticate_admin!
    @project = find_project(params[:id])
    @project.public_viewable = false
    @project.save
    render "/admin/hide_project_for_public.js".to_sym, :layout => false
  end

  get "/show_project_for_public/:id", :provides => [:js] do
    authenticate_admin!
    @project = find_project(params[:id])
    @project.public_viewable = true
    @project.save
    render "/admin/hide_project_for_public.js".to_sym, :layout => false
  end


  get "/check-updates", :provides => [:js] do
    authenticate_admin!
    
    version_obj = retrieve_buildwise_version_json
    if version_obj.nil?

      @error = "failed"

    else
      @new_version = version_obj["version"]

      @current_version = ::BuildWise::VERSION
      
      my_revision = Revision.new(@current_version)
      server_revision = Revision.new(@new_version)
      logger.info("raw versions: #{@current_version} vs #{@new_version} ")
      
      if my_revision.to_s == server_revision.to_s

        logger.debug("Number version are the same")
        @new_version_available =  @current_version < @new_version 
      else
        @new_version_available  = my_revision < server_revision
      end

      logger.info("Compare version: #{my_revision} vs #{server_revision} => #{@new_version_available}")
    end
    render "/admin/check_updates.js", :layout => false
  end

  get "/upgrade", :provides => [:js] do
    authenticate_admin!
    
    quick_mode = params[:mode] == "quick"
    
    version_obj = retrieve_buildwise_version_json
    @version = version_obj["version"]
    new_release_url = version_obj["url"]
    logger.debug("Downloading: #{new_release_url}")

    @error = nil
    @upgrade_ok = false

    begin
      OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
      new_version_file = File.basename(new_release_url)
      file_path = File.join(BUILDWISE_ROOT, "tmp", new_version_file)
      download_file_httparty(new_release_url, file_path)
      logger.info("Download is complete")
    rescue => e
      @error = "Failed to download the release, #{e}"
      logger.warn("Download failed: #{e}")   
    end

    require 'digest'
    require 'digest/md5'

    sha256_hash = Digest::SHA256.file(file_path).hexdigest
    

      if @error.nil? && ( sha256_hash == version_obj["sha256"] )
        begin
          parent_dir = File.join(BUILDWISE_ROOT, "..")
          Archive::Zip.extract(file_path, parent_dir)

          @new_release_root = File.expand_path(File.join(parent_dir, "buildwise-#{@version}"))

          if BUILDWISE_ROOT == @new_release_root

             
          else     


            FileUtils.cp( File.join(BUILDWISE_ROOT, "startup.bat"), File.join(@new_release_root, "startup.bat") )
            FileUtils.cp( File.join(BUILDWISE_ROOT, "config", "database.yml"), File.join(@new_release_root, "config", "database.yml") )


            if File.exist?(File.join(BUILDWISE_ROOT, "config", "server.digest"))

              FileUtils.copy_entry(File.join(BUILDWISE_ROOT, "config", "server.digest"), File.join(@new_release_root, "config", "server.digest"), preserve: true)        
            end
        
            if  quick_mode
              new_artifact_dir =  File.join(@new_release_root, "public", "artifacts")
              if File.exist?(new_artifact_dir)
                FileUtils.rm_rf(new_artifact_dir)
              end        
              if Dir.exist?(File.join(BUILDWISE_ROOT, "public", "artifacts"))
                FileUtils.mv File.join(BUILDWISE_ROOT, "public", "artifacts"),  File.join(@new_release_root, "public")        
              end
            else
              puts("[INFO] Full Mode copy artifacts")

              FileUtils.cp_r File.join(BUILDWISE_ROOT, "public", "artifacts/."),  File.join(@new_release_root, "public", "artifacts")
            end
                
            @upgrade_ok = true
          end
          
        rescue => ioe
          @upgrade_ok = false
          @error = "Install new version error, #{ioe}"
        end
      else
        @upgrade_ok = false
        @error = "SHA256 hash dot not match."
      end


      buildwise_dir = "/var/www/sinatra/buildwise"
      


      @testwisely_deploy = false
      if @upgrade_ok &&  RUBY_PLATFORM.include?("linux") &&  ENV["SERVER_DIGEST"] && ENV["SERVER_DIGEST"].size > 7
        if File.symlink?(buildwise_dir) && Dir.exist?(buildwise_dir) && 
          Dir.exist?(@new_release_root) &&  File.readlink(buildwise_dir) != @new_release_root
          FileUtils.rm(buildwise_dir)
          `ln -s #{@new_release_root} #{buildwise_dir}`
          FileUtils.mkdir(File.join(@new_release_root, "public", "tmp"))
          `touch #{buildwise_dir}/public/tmp/restart.txt`
          @testwisely_deploy = true

        end      
      end
    
    render  "/admin/upgrade.js", :layout => false
  end


  get "/permissions" do
    authenticate_admin!

    render "/admin/permissions"
  end



	get "sandbox" do
    render "/admin/sandbox"	
	end
		
end