class Api::V1::BaseController < ApplicationController

  include Api::ProjectHelper
  include Api::UserHelper
  include Api::PullHelper

  # before_action :doorkeeper_authorize!
  # skip_before_action :user_setup

  protected 
  # def current_user
  #   #client方法对接，需要一直带着用户标识uid
  #   Rails.logger.info doorkeeper_token
  #   if doorkeeper_token && doorkeeper_token.resource_owner_id.blank?
  #     # return User.anonymous if params[:uid].nil?
  #     # tip_exception("2222")
  #     # return render_error('缺少用户标识!')  if params[:uid].nil?
  #     User.current = User.find(params[:uid])
  #   else
  #     User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
  #   end
  # end

  def kaminary_select_paginate(relation)
		limit = params[:limit] || params[:per_page]
		limit = (limit.to_i.zero? || limit.to_i > 200) ? 200 : limit.to_i
		page  = params[:page].to_i.zero? ? 1 : params[:page].to_i

		relation.page(page).per(limit)
	end
  
  def limit
    params.fetch(:limit, 15) 
  end

  def page 
    params.fetch(:page, 1)
  end

  def load_organization
    @organization = Organization.find_by(login: params[:owner]) || Organization.find_by(id: params[:owner])
    return render_not_found("组织不存在") if @organization.nil?
  end

  # 具有对仓库的管理权限
  def require_manager_above
    @project = load_project
    return render_forbidden if !current_user.admin? && !@project.manager?(current_user)
  end

  # 具有对仓库的操作权限
  def require_operate_above 
    @project = load_project
    return render_forbidden if !current_user.admin? && !@project.operator?(current_user)
  end

  # 具有仓库的操作权限或者fork仓库的操作权限
  def require_operate_above_or_fork_project 
    @project = load_project
    return render_forbidden if !current_user.admin? && !@project.operator?(current_user) && !(@project.fork_project.present? && @project.fork_project.operator?(current_user))
  end

  def require_member_above 
    @project = load_project 
    return render_forbidden if !current_user.admin? && !@project.member?(current_user)
  end

  # 具有对仓库的访问权限
  def require_public_and_member_above
    @project = load_project
    return render_forbidden if !@project.is_public && !current_user.admin? && !@project.member?(current_user)
  end
end