# == Schema Information
#
# Table name: versions
#
#  id                  :integer          not null, primary key
#  project_id          :integer          default("0"), not null
#  name                :string(255)
#  description         :text(65535)
#  effective_date      :date
#  created_on          :datetime
#  updated_on          :datetime
#  wiki_page_title     :string(255)
#  status              :string(255)      default("open")
#  sharing             :string(255)      default("none"), not null
#  user_id             :integer
#  issues_count        :integer          default("0")
#  closed_issues_count :integer          default("0")
#  percent             :float(24)        default("0")
#
# Indexes
#
#  index_versions_on_sharing  (sharing)
#  versions_project_id        (project_id)
#

class Version < ApplicationRecord
  include DunCheckAble
  belongs_to :project, counter_cache: true, touch: true
  has_many :issues, class_name: "Issue", foreign_key: "fixed_version_id"
  belongs_to :user, optional: true

  has_many :opened_issues, -> {where(issue_classify: "issue").where.not(status_id: 5)}, class_name: "Issue", foreign_key: :fixed_version_id
  has_many :closed_issues, -> {where(issue_classify: "issue", status_id: 5)}, class_name: "Issue", foreign_key: :fixed_version_id

  scope :version_includes, ->{includes(:issues, :user)}
  scope :closed, ->{where(status: 'closed')}
  scope :opening, ->{where(status: 'open')}

  # def open_issues_count
  #   issues.select(:id,:status_id).where(status_id: [1,2,3,4,6]).size
  # end
  #
  # def close_issues_count
  #   issues.select(:id,:status_id).where(status_id: 5).size
  # end

  after_create :send_create_message_to_notice_system
  after_save :send_update_message_to_notice_system

  def issue_percent 
    issues_total_count = opened_issues.size + closed_issues.size
    issues_total_count.zero? ? 0.0 : closed_issues.size.to_f / issues_total_count
  end

  def version_user
    User.select(:login, :lastname,:firstname, :nickname)&.find_by_id(self.user_id)
  end

  def to_builder 
    Jbuilder.new do |version|
      version.(self, :id, :name, :description, :effective_date)
    end
  end

  private 
  def send_create_message_to_notice_system
    SendTemplateMessageJob.perform_later('ProjectMilestone', self.id, self.user_id) if Site.has_notice_menu?
  end

  def send_update_message_to_notice_system
    SendTemplateMessageJob.perform_later('ProjectMilestoneCompleted', self.id) if Site.has_notice_menu? && self.issue_percent == 1.0
    SendTemplateMessageJob.perform_later('ProjectMilestoneEarlyExpired', self.id) if Site.has_notice_menu? && self.effective_date == Date.today + 1.days 
    SendTemplateMessageJob.perform_later('ProjectMilestoneExpired', self.id) if Site.has_notice_menu? && self.effective_date == Date.today - 1.days 
  end
end
