class Api::V1::Projects::CompareController < Api::V1::BaseController 

  before_action :require_public_and_member_above, only: [:files]

  def files 
    load_compare_params
    if params[:type] == "sha"
      @compare_result ||= gitea_compare_files(@base, @head)
    else
      @compare_result ||= @head.include?(":") ? gitea_compare_files(@base, @head) : gitea_compare_files(@head, @base)
      @merge_status, @merge_message = get_merge_message
    end
  end

  private 
  def load_compare_params
    @base = params[:base].include?(":") ? Addressable::URI.unescape(params[:base].split(":")[0]) + ':' + Base64.decode64(params[:base].split(":")[1]) : Base64.decode64(params[:base])
    @head = params[:head].include?(":") ? Addressable::URI.unescape(params[:head].split(":")[0]) + ':' + Base64.decode64(params[:head].split(":")[1]) : Base64.decode64(params[:head])
  end

  def gitea_compare_files(base, head)
    if params[:filepath].present?
      $gitea_hat_client.get_repos_compare_by_owner_repo_baseref_headref(@project&.owner&.login, @project.identifier, Addressable::URI.escape(base), Addressable::URI.escape(head), {query: {token: current_user&.gitea_token, isFiles: true, filepath: params[:filepath]}})
    else
      $gitea_hat_client.get_repos_compare_by_owner_repo_baseref_headref(@project&.owner&.login, @project.identifier, Addressable::URI.escape(base), Addressable::URI.escape(head), {query: {page:page,limit:limit,token: current_user&.gitea_token, isFiles: true}})
    end
  end

  def get_merge_message
    if @base.blank? || @head.blank?
      return -2, "请选择分支"
    else
      return -2, "目标仓库未开启合并请求（PR）功能" unless @project.has_menu_permission("pulls")
      if @head.include?(":")
        fork_project = @project.forked_projects.joins(:owner).where(users: {login: @head.to_s.split("/")[0]}).take
        return -2, "请选择正确的仓库" unless fork_project.present?
        @exist_pullrequest = @project.pull_requests.where(is_original: true, head: @head.to_s.split(":")[1], base: @base, status: 0, fork_project_id: fork_project.id).take
      else 
        @exist_pullrequest = @project.pull_requests.where(is_original: false, head: @base, base: @head, status: 0).take
      end
      if @exist_pullrequest.present?
        return -2, "在这些分支之间的合并请求已存在：<a href='/#{@owner.login}/#{@project.identifier}/pulls/#{@exist_pullrequest.id}'>#{@exist_pullrequest.try(:title)}</a>"
      else 
        Rails.logger.info @compare_result
        if params[:filepath].present? 
          if @compare_result["Commits"].blank? && @compare_result["Diff"].blank?
            return -2, "分支内容相同，无需创建合并请求"
          end
        else
          if @compare_result[:total_data].to_i < 1 
            return -2, "分支内容相同，无需创建合并请求"
          end
        end
      end
    end
    return 0, "可以合并"
  end
end