require File.expand_path('../../spec_helper', __FILE__)

describe 'EasyIssueQuery', :logged => :admin do
  let(:project) { FactoryGirl.create(:project) }
  let(:project_two) { FactoryGirl.create(:project) }
  let!(:custom_field) { FactoryGirl.create(:issue_custom_field, :projects => [project.id], :is_for_all => false, :visible => true) }
  let!(:custom_field_two) { FactoryGirl.create(:issue_custom_field, :projects => [project_two.id], :is_for_all => false, :visible => true) }
  let!(:custom_field_for_all) { FactoryGirl.create(:issue_custom_field, :visible => true) }

  describe '#available_columns' do
    context 'when project specific query' do
      it 'contains only CFs for its project or for all projects' do
        query = EasyIssueQuery.new(:name => '_', :project => project)
        query_custom_field_columns = query.available_columns.select{|cf| cf.is_a?(EasyQueryCustomFieldColumn)}
        custom_field_two_detected = query_custom_field_columns.detect{|col| col.custom_field == custom_field_two}

        expect(query_custom_field_columns.count).to eq(2)
        expect(custom_field_two_detected).to be_nil
      end
    end

    context 'when global query' do
      it 'contains only CFs for all projects' do
        query = EasyIssueQuery.new(:name => '_')
        query_custom_field_columns = query.available_columns.select{|cf| cf.is_a?(EasyQueryCustomFieldColumn)}

        expect(query_custom_field_columns.count).to eq(3)
      end
    end
  end

  describe '#additional_group_attributes' do
    context 'when group entity count is nil' do
      it 'returns zero percent' do
        query = EasyIssueQuery.new(:group_by => 'assigned_to')
        attributes = {:count => nil}
        query.additional_group_attributes(nil, attributes, nil)
        expect(attributes[:percent]).to eq(0)
      end
    end
  end

  describe 'scope testing' do

    it 'tracker in order condition without group or column' do
      q = EasyIssueQuery.new(name: 'My', column_names: [:subject, :project, :done_ratio, :due_date])
      expect(q.create_entity_scope(order: ['trackers']).count).to eq(2)
    end

  end
end
