class Traces::ProjectsController < Traces::BaseController
  include OperateProjectAbilityAble

  before_action :require_login
  before_action :load_project
  before_action :require_project_not_be_forked_project
  before_action :set_trace_token_to_cookie
  before_action :authorizate_user_can_edit_project!, except: [:task_results]

  def tasks 
    branch_name = params[:branch_name]
    return render_error("无可用检测次数") if @project.user_trace_tasks.size >= 5
    return render_error("分支名不能为空！") if branch_name.blank?
    @all_branches = Gitea::Repository::Branches::ListNameService.call(@project&.owner, @project.identifier)
    return render_error("请输入正确的分支名！") unless @all_branches.include?(branch_name) 
    code, data, error = Trace::CheckService.call(current_user.trace_token, @project, "1", branch_name)
    if code == 200 
      UserTraceTask.create!(
        user_id: current_user.id,
        project_id: @project.id, 
        branch_tag: branch_name,
        task_id: data["task_id"]
      )
      render_ok
    else 
      render_error("检测失败 Error:#{error}")
    end
  rescue Exception => exception
    puts exception.message
    normal_status(-1, exception.message)
  end

  def task_results
    limit = params[:limit] || params[:per_page]
		limit = (limit.to_i.zero? || limit.to_i > 15) ? 15 : limit.to_i
		page  = params[:page].to_i.zero? ? 1 : params[:page].to_i
    return render :json => {left_tasks_count: 5, data: []} if current_user.trace_user.nil?
    code, data, error = Trace::CheckResultService.call(current_user.trace_token, @project, nil, page, limit)
    if code == 200
      render :json => {left_tasks_count: 5 - @project.user_trace_tasks.size, data: data, view_base: "#{Trace.trace_config[:view_domain]}/analysis_ccf/analysis-results/" }
    else 
      render_error("获取检测记录失败 Error:#{error}")
    end
  rescue Exception => exception 
    puts exception.message
    normal_status(-1, exception.message)
  end

  def reload_task 
    return render_error("project_id错误") if params[:project_id].blank?
    branch_name = params[:branch_name]
    return render_error("分支名不能为空！") if branch_name.blank?
    @all_branches = Gitea::Repository::Branches::ListNameService.call(@project&.owner, @project.identifier)
    return render_error("请输入正确的分支名！") unless @all_branches.include?(branch_name) 
    code, data, error = Trace::ReloadCheckService.call(current_user.trace_token, params[:project_id])
    if code == 200 
      UserTraceTask.create!(
        user_id: current_user.id,
        project_id: @project.id, 
        branch_tag: branch_name,
        task_id: data["task_id"]
      )
      render_ok 
    else 
      render_error("重新检测失败 Error:#{error}")
    end
  rescue Exception => exception 
    puts exception.message
    normal_status(-1, exception.message)
  end


  def task_pdf 
    task_id =  params[:task_id]
    return render_error("task_id错误") if task_id.blank?
    file_save_path = "public/trace_task_results/#{task_id}/report.pdf" 
    if File.exists?(file_save_path)
      redirect_to "/trace_task_results/#{task_id}/report.pdf"
    else 
      result = Trace::PdfReportService.call(current_user.trace_token, task_id)
      if result.is_a?(Hash) && result[:code] == 200
        redirect_to result[:download_url]
      else 
        render_error("下载报告失败！")
      end
    end
  rescue Exception => exception 
    puts exception.message
    normal_status(-1, exception.message)
  end

  def set_trace_token_to_cookie
    cookies[:vue_admin_template_token] = {
      :value => current_user&.trace_token,
      :expires => 1.hours.from_now,
      :domain => Trace.trace_config[:cookie_domain]
    }
  end

  def require_project_not_be_forked_project
   return render_error('fork仓库暂不支持代码溯源服务，敬请谅解。') if @project.forked_from_project_id.present?
  end
end