require_relative '../spec_helper'

RSpec.feature 'Dashboard filters', js: true, logged: :admin do

  let(:issue_this_year) { FactoryGirl.create(:issue, start_date: Date.today) }
  let(:issue_prev_year) { FactoryGirl.create(:issue, start_date: (Date.today-1.year)) }

  # Add module "Tasks from filters"
  def add_issue_query_module
    find('.customize-button').click
    first('.add-module-select option', text: I18n.t('easy_pages.modules.issue_query')).select_option
    wait_for_ajax
    find('.save-modules-back').click
  end

  # Add global date filter (start_date is affected)
  def add_global_date_filter
    find('.tab-controls__edit').click
    wait_for_ajax
    find('.tab-controls__select-type option[value="date_period"]').select_option
    first('.tab-controls__filter-def input[type="text"]').set('NewGlobalFilterWhichIsUniq')
    first('.tab-controls__filter-use option[value="start_date"]').select_option
    find('.tab-controls__form a.apply-link').click
  end

  def test_global_date_filter
    expect(Issue.count).to eq(0)
    issue_this_year
    issue_prev_year

    # Get issues from this year
    find('.tab-filter__field select option[value="current_year"]').select_option
    find('.tab-filter__apply').click
    wait_for_ajax

    within find('.entities') do
      expect(page).to     have_selector('.issue', count: 1)
      expect(page).to     have_text(issue_this_year.subject)
      expect(page).to_not have_text(issue_prev_year.subject)
    end

    # Get issues from previous year
    find('.tab-filter__field select option[value="last_year"]').select_option
    find('.tab-filter__apply').click
    wait_for_ajax

    within find('.entities') do
      expect(page).to     have_selector('.issue', count: 1)
      expect(page).to_not have_text(issue_this_year.subject)
      expect(page).to     have_text(issue_prev_year.subject)
    end
  end

  it 'Normal page' do
    visit home_path

    add_issue_query_module
    add_global_date_filter
    test_global_date_filter
  end

  it 'Template page' do
    my_page_template = EasyPageTemplate.find_by(template_name: 'my-page-template')
    visit easy_page_templates_show_page_template_path(id: my_page_template.id)

    add_issue_query_module
    add_global_date_filter

    expect(page).to     have_selector('.tab-filter__field')
    expect(page).to_not have_field('.tab-filter__field select')

    EasyPageZoneModule.create_from_page_template(my_page_template, User.current.id)

    visit home_path

    test_global_date_filter
  end

end
