class Myshixun < ApplicationRecord
  include ApplicationHelper
  has_many :games, :dependent => :destroy
  has_many :student_works
  has_one :shixun_modify, :dependent => :destroy

  belongs_to :user
  belongs_to :shixun, counter_cache: true

  validates_uniqueness_of :shixun_id, :scope => :user_id, :message => "shixun_id and user_id unique error"
  scope :finished, lambda { where(status: 1) }
  scope :search_myshixun_user, ->(user_id){where(user_id:user_id)}


  def owner
    self.user
  rescue ActiveRecord::RecordNotFound
  end

  def output_times
    games.sum(:evaluate_count)
  end

  def repo_path
    "#{self.repo_name}.git"
  end

  def is_complete?
    self.status == 1
  end

  # 判断TPM的代码是否被修改了
  # 判断依据是看tpm的最新提交记录和tpi数据库中存储的commit_id是否一致
  def repository_is_modified shixun_repo_path
    myshixun_commit_id = self.commit_id
    if myshixun_commit_id.blank?
      myshixun_commit_id = GitService.commits(repo_path: self.repo_path).last["id"]
      self.update_column(:commit_id, myshixun_commit_id)
    end
    shixun_commit_id = GitService.commits(repo_path: shixun_repo_path).first["id"]
    Rails.logger.warn("###############shixun_commit_id is #{shixun_commit_id}")
    Rails.logger.warn("###############myshixun_commit_id is #{self.commit_id}")
    result = myshixun_commit_id != shixun_commit_id ? true :false
    return result
  end

  def mirror_name
    self.shixun.mirror_repositories.map(&:type_name).blank? ? "" : self.shixun.mirror_repositories.map(&:type_name)
  end

  def main_mirror
    self.shixun.mirror_repositories.published_main_mirror.try(:first)
  end

  # 当前任务:一个实训中只可能一个未完成任务(status 0或1只会存在一条记录)
  # status:0 可以测评的,正在测评的
  # 如果都完成,则当前任务为最后一个任务
  def current_task
    games = self.games
    current_game = games.select{|game| game.status == 1 || game.status == 0}.first
    if current_game.blank?
      current_game = Game.find_by_sql("SELECT g.* FROM games g, challenges c where g.myshixun_id=#{self.id}
                                       and g.challenge_id = c.id and g.status = 2 order by c.position desc").first
    end
    current_game
  end


  # 挑战至第几关(已完成关卡数+1)
  def exec_count
    gcount = self.games.select{|game| game.status == 2}.size
    gcount = gcount < self.games.size ? (gcount + 1) : gcount
  end

  # 个人实训得分
  def total_score
    self.games.where("status = 2 and final_score > 0").sum(:final_score).to_i
  end

  # 个人通关数
  def passed_count
    self.games.where(status: 2).count
  end

  # 通关时间
  def passed_time
    self.status == 1 ? self.games.map(&:end_time).max : "--"
  end

  # 耗时
  def total_spend_time
    game_spend_time self.games.where(status: 2).sum(:cost_time).to_i
  end

  # 通关总耗时
  def total_cost_time
    self.games.where(status: 2).sum(:cost_time).to_i
  end

end