module EasyAgileControllerMethods

  def self.included(base)
    base.class_eval do
      cattr_accessor :assignment_class_name
    end
  end

  def assignment_class
    assignment_class_name.constantize
  end

  def phase_scope
    if params[:phase] == 'project_backlog'
      EasyAgileBacklogRelation.where(project_id: @easy_sprint.project_id)
    else
      assignment_class.with_phase(params[:phase])
    end
  end

  def reorder
    return head :ok unless params[:issue_ids].present?
    @positions = Issue.where(id: params[:issue_ids]).joins(:priority).order('enumerations.position desc').pluck("#{Issue.table_name}.id").each_with_index.map{|id, index| {issue_id: id, position: index + 1}}
    @relations = {}
    phase_scope.where(issue_id: params[:issue_ids]).map{|x| @relations[x.issue_id] = x}
    @positions.each do |position|
      @relations[position[:issue_id]].update_columns(position: position[:position]) if @relations[position[:issue_id]]
    end
    respond_to do |format|
      format.api { render template: 'easy_kanban/priority_positions' }
    end
  end

  def count_position(entity, options = {})
    if options[:phase] == 'project_backlog'
      klass = EasyAgileBacklogRelation
      current = entity.position if entity && !entity.new_record?
    else
      klass = assignment_class
      current = entity.position if entity && !entity.phase_column_value_changed?
    end
    position ||= klass.where(issue_id: options[:prev_item_id]).limit(1).pluck(:position).first.to_i + 1 if options[:prev_item_id].present?
    position ||= klass.where(issue_id: options[:next_item_id]).limit(1).pluck(:position).first.to_i if options[:next_item_id].present?
    position -= 1 if current && position && current <= position
    position || current
  end

end
