class EasyEntityActivity < ActiveRecord::Base
  include Redmine::SafeAttributes

  belongs_to :entity, polymorphic: true, validate: false
  belongs_to :issue, ->{ joins("INNER JOIN #{EasyEntityActivity.table_name} ON #{EasyEntityActivity.table_name}.entity_type = 'Issue' AND #{EasyEntityActivity.table_name}.entity_id = #{Issue.table_name}.id")}, foreign_key: :entity_id
  alias_method :issue, :entity
  belongs_to :category, class_name: 'EasyEntityActivityCategory'
  belongs_to :author, class_name: 'User'

  validates :entity, :presence => true
  validates :category, :presence => true

  attr_accessor :journal_note

  before_save :update_entity
  before_save :prepare_update_entity

  has_many :easy_entity_activity_attendees, dependent: :destroy

  scope :sorted, -> { order(start_time: :desc) }

  safe_attributes 'author_id', 'category_id', 'is_finished', 'description', 'entity_id', 'entity_type', 'all_day', 'start_time'

  delegate :project, to: :entity

  attr_protected :id

  def update_entity
    details = { time: format_time(self.start_time), category: self.category}
    if self.new_record?
      @journal_note = (self.is_finished? ? l(:easy_entity_activity_was_reported, details) : l(:easy_entity_activity_is_planned, details)) + " : #{description}"
    elsif self.is_finished_changed?
      @journal_note = l(:easy_entity_activity_was_finished, details) + " : #{description}"
    end
  end

  def planned?
    persisted? && start_time && (created_at < start_time)
  end

  def prepare_update_entity
    entity.init_journal(User.current, @journal_note) if @journal_note.present?
    entity.save
  end

  def start_date
    User.current.time_to_date(start_time)
  end

  def start_time=(value)
    super(EasyUtils::DateUtils.build_datetime_from_params(value))
  end

  def css_classes(user=nil, options={})
    user ||= User.current
    inline_editable = options[:inline_editable] != false
    if user.logged?
      s = ''
      s << ' created-by-me' if self.author_id == user.id
      s << ' multieditable-container' if inline_editable
    end
    s
  end

  def assignable_users
    User.active.sorted
  end
end

