# == Schema Information
#
# Table name: pull_requests
#
#  id                      :integer          not null, primary key
#  gitea_id                :integer
#  gitea_number            :integer
#  user_id                 :integer
#  created_at              :datetime         not null
#  updated_at              :datetime         not null
#  status                  :integer          default("0")
#  project_id              :integer
#  title                   :string(255)
#  milestone               :integer
#  body                    :text(4294967295)
#  head                    :string(255)
#  base                    :string(255)
#  issue_id                :integer
#  fork_project_id         :integer
#  is_original             :boolean          default("0")
#  comments_count          :integer          default("0")
#  commits_count           :integer          default("0")
#  files_count             :integer          default("0")
#  fork_project_owner      :string(255)
#  fork_project_identifier :string(255)
#

class PullRequest < ApplicationRecord
  #status 0 默认未合并， 1表示合并, 2表示请求拒绝(或已关闭) ,3 表示未签署CLA
  include DunCheckAble
  #status 0 默认未合并， 1表示合并, 2表示请求拒绝(或已关闭)
  OPEN   = 0
  MERGED  = 1
  CLOSED = 2
  NEEDCLA = 3

  belongs_to :issue
  belongs_to :user
  belongs_to :project, counter_cache: true, touch: true, optional: true
  belongs_to :fork_project, class_name: 'Project', foreign_key: :fork_project_id, optional: true
  has_many :pull_request_assigns, foreign_key: :pull_request_id
  has_many :pull_request_tags, foreign_key: :pull_request_id
  has_many :project_trends, as: :trend, dependent: :destroy
  has_many :attachments, as: :container, dependent: :destroy
  has_one :gitea_pull, foreign_key: :id, primary_key: :gitea_id, class_name: 'Gitea::Pull'
  has_many :journals, :as => :journalized, :dependent => :destroy
  has_many :journal_details, through: :journals
  has_many :reviews, dependent: :destroy
  has_many :pull_requests_reviewers, dependent: :destroy
  has_many :reviewers, through: :pull_requests_reviewers
  has_many :mark_files, dependent: :destroy
  has_many :pull_attached_issues, dependent: :destroy
  has_many :attached_issues, through: :pull_attached_issues, source: :issue

  scope :merged_and_closed, ->{where.not(status: 0)}
  scope :opening, -> {where(status: 0)}

  after_create :incre_project_common, :incre_user_statistic, :incre_platform_statistic
  after_destroy :decre_project_common, :decre_user_statistic, :decre_platform_statistic

  def incre_project_common
    CacheAsyncSetJob.perform_later("project_common_service", {pullrequests: 1}, self.project_id)
  end

  def decre_project_common
    CacheAsyncSetJob.perform_later("project_common_service", {pullrequests: -1}, self.project_id)
  end

  def incre_user_statistic 
    CacheAsyncSetJob.perform_later("user_statistic_service", {pullrequest_count: 1}, self.user_id)
  end

  def decre_user_statistic
    CacheAsyncSetJob.perform_later("user_statistic_service", {pullrequest_count: -1}, self.user_id)
  end

  def incre_platform_statistic
    CacheAsyncSetJob.perform_later("platform_statistic_service", {pullrequest_count: 1})
  end

  def decre_platform_statistic
    CacheAsyncSetJob.perform_later("platform_statistic_service", {pullrequest_count: -1})
  end

  def fork_project
    Project.find_by(id: self.fork_project_id)
  end

  def bind_gitea_pull_request!(gitea_pull_number, gitea_pull_id)
    update_columns(
      gitea_number: gitea_pull_number,
      gitea_id: gitea_pull_id)
  end

  def merge!
    update_column(:status, PullRequest::MERGED)
  end

  def project_trend_status!
    self&.project_trends&.update_all(action_type: ProjectTrend::CLOSE)
  end

  # TODO: sync educoder platform repo's for update some statistics count
  def self.update_some_count
    PullRequest.includes(:user, :project).select(:id, :user_id, :gitea_number, :project_id, :fork_project_id).each do |pr|
      puts pr.id
      next if pr.gitea_number.blank?
      project = pr.project

      next if project.blank?
      user = project.owner
      next  if pr.gitea_number === 6 || pr.gitea_number === 7
      files_result = Gitea::PullRequest::FilesService.call(user.login, project.identifier, pr.gitea_number)
      pr.update_column(:files_count, files_result['NumFiles']) unless files_result.blank?

      commits_result = Gitea::PullRequest::CommitsService.call(user.login, project.identifier, pr.gitea_number)
      pr.update_column(:commits_count, commits_result.size) unless commits_result.blank?
    end
  end

  def conflict_files
    file_names = self&.gitea_pull&.conflicted_files
    return [] if file_names.blank?

    JSON.parse file_names
  end

  def to_builder
    Jbuilder.new do |pull|
      pull.(self, :id, :gitea_number, :title, :body, :base, :head, :is_original, :comments_count)
      pull.user self.user.to_builder
      if self.fork_project.present?
        pull.fork_project self.fork_project.to_builder
      else
        pull.fork_project nil
      end
      pull.created_at self.created_at.strftime("%Y-%m-%d %H:%M")
      pull.updated_at self.updated_at.strftime("%Y-%m-%d %H:%M")
      pull.status self.pr_status
      pull.url self.pr_url
    end
  end

  def pr_url
    return nil if self.project.nil?
    "#{Rails.application.config_for(:configuration)['platform_url']}/#{self.project.owner.login}/#{self.project.name}/pulls/#{self.id}"
  end

  def closed?
    self.status == CLOSED
  end

  def merged?
    self.status == MERGED
  end

  def opened?
    self.status == OPEN
  end

  def pr_status
    case status
    when 0
      "OPEN"
    when 1
      "MERGED"
    when 2
      "CLOSED"
    end
  end

end
