class Management < ApplicationRecord
  belongs_to :user
  belongs_to :expedient, touch: true
  belongs_to :management_category, optional: true
  has_many :comments, dependent: :destroy
  has_many :assets, as: :assetable, dependent: :destroy
  has_many :events, as: :eventable, dependent: :destroy

  validates :kind, :comment, presence: true

  scope :newer, -> { order(created_at: :desc) }
  scope :closed, -> { where(state: 'closed') }
  scope :news, -> { where(state: 'new') }
  scope :kind, -> (kind) { where(kind: kind) }
  scope :for_assigned, -> (user_id) { where('assigned_ids @> ?', "{#{user_id}}").pluck(:id) }

  delegate :complaint?, :claim?, :notice?, :suggestion?, :congratulation?, :request?, to: :current_state
  delegate :new?, :process?, :closed?, to: :current_state

  after_create :notify_users

  KIND = {
    'complaint' => 'Queja',
    'notice' => 'Aviso',
    'claim' => 'Reclamo',
    'request' => 'Petición',
    'query' => 'Consulta',
    'suggestion' => 'Sugerencia',
    'congratulation' => 'Felicitación',
  }

  def assigned_names
    @assigned_names ||= User.where(id: assigned_ids).pluck(:name, :administrative_area).map{|o| o[1].blank? ? o[0] : "#{o[0]} (#{o[1]})"}.join(', ')
  end

  def statistics_assigned_names
    all_ids = assigned_ids.map{|id| id.nil? ? user_id : id}
    User.where(id: all_ids).pluck(:name, :administrative_area).map{|o| o[1].blank? ? o[0] : "#{o[0]} (#{o[1]})"}.join(', ')
  end

  def current_kind
    self.kind.inquiry
  end

  def current_state
    self.state.inquiry
  end

  def kind_s
    KIND[self.kind]
  end

  def full_classification
    fc = KIND[self.kind].upcase
    fc << " (#{self.try(:management_category).try(:name)})" if self.management_category_id.present?
    fc
  end

  def notify_users
    unless Rails.env.development?
      User.where(id: assigned_ids).each do |assigned_user|
        ApplicationMailer.notify_new_management(self, assigned_user).deliver_now
      end
    end
  end

  ransacker :assigned_ids do
    Arel.sql("array_to_string(managements.assigned_ids, ',')")
  end

  def closed_at
    events.where(state: 'closed').first.try(:start_at)
  end

  # ransacker :administrative_area, args: [:parent, :ransacker_args] do |parent, args|
  #
  #   user_ids = User.where(administrative_area: "UDS MINSAL").ids
  #   #Expedient.joins(:managements).where('managements.assigned_ids && ARRAY[?]::integer[]', )
  #   where('managements.assigned_ids && ARRAY[?]::integer[]', user_ids)
  # end


end
