require 'rails_helper'

RSpec.feature "Admin manages user" do
  let(:user_options){ Hash.new }
  let!(:admin) { create :admin, user_options.merge(email: 'admin@example.com') }
  #let(:user) { create :user, user_options.merge(email: 'user@example.com') }
  background { i_am_logged_in_as user }

  context "With manage user rights" do
    let(:user) { create(:user, email: 'user@example.com', role_names_admin: ['manage-class-User']) }

    scenario 'list users' do
      user and click_on "Gebruikers"
      expect(page).to have_content('admin@example.com')
      expect(page).to have_content('user@example.com')
    end

    scenario "create new user" do
      click_on "Gebruikers"
      click_on "Gebruiker toevoegen"
      fill_in 'Email', with: "new_user@example.com"
      fill_in 'Password', with: "password123"

      #find('#user-role-migration-read').set true
      #find('#user-role-owner-read').set true
      #find('#user-role-service_provider-read').set true
      #find('#user-role-contractor-manage').set true
      #find('#user-role-report-timewax').set true
      #check 'Role1'
      #check 'Role2'
      click_on "Gebruiker toevoegen"

      expect(current_path).to eq dunlop.users_path

      user = User.find_by(email: 'new_user@example.com')
      expect( admin ).to_not eq user

      expect( user.valid_password?('password123')) .to be true
      expect( user.role_names.map(&:presence).compact ).to match_array %w[read-class-WorkflowInstance]
      #expect(user.roles).to eq [Role::Role1, Role::Role2, '']
    end

    scenario "edit user" do
      other_user = create :user, email: 'other-user@example.com'
      click_on "Gebruikers"

      within "#user-#{other_user.id}" do
        click_on_selector ".table-link.edit"
      end
      # Clear all permissions (empty value ...)
      #find('#user-role-migration-read').set false
      #click_on "Update"
      click_on "Gebruiker bijwerken"

      expect(current_path).to eq "/dunlop/users"
      expect(other_user.reload.role_names).to eq ["", "read-class-WorkflowInstance"]
    end

    scenario "show permissions table" do
      visit "/dunlop/users/permissions_table"
      page.should have_selector '.role-icon.read'
    end
  end
end


