# == Schema Information
#
# Table name: user_clas
#
#  id         :integer          not null, primary key
#  user_id    :integer          not null
#  cla_id     :integer          not null
#  real_name  :string(255)      not null
#  email      :string(255)      not null
#  state      :integer          default("0")
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  sign_time  :datetime
#
# Indexes
#
#  index_user_clas_on_cla_id   (cla_id)
#  index_user_clas_on_user_id  (user_id)
#

class UserCla < ApplicationRecord
    belongs_to :user
    belongs_to :cla
# identity 0: 教师教授 1: 学生, 2: 专业人士, 3: 开发者
    enum state: { deafult: 0, signed: 1, failed: 2}
 
    after_save do
        cla.fresh_count
    end

    before_save do
        fresh_pull_request
    end

    def self.build(params,current_user_id)
        self.create!(user_id: current_user_id,
                    cla_id: params[:cla_id],
                    real_name: params[:real_name], 
                    email: params[:email],
                    sign_time: Time.now,
                    state: 1
                )
    end

    def update_by_params(params)
        update(\
            state: 1,
            sign_time: Time.now,
            real_name: params[:real_name], 
            email: params[:email],
        )
    end

    def fresh_pull_request
        project_ids = cla.organization.projects.pluck(:id)
        if state == "signed"
            PullRequest.where(user_id: user_id, project_id: project_ids, status:3).update_all(status:0)
        else
            PullRequest.where(user_id: user_id, project_id: project_ids, status:0).update_all(status:3)
        end
    end

end
