require 'spec_helper'

describe "Account School", :js => true, :type => :feature, :capybara_feature => true do

  subject { page }

  let(:user) {FactoryGirl.create(:user)}
  let(:school) {FactoryGirl.create(:school) }
  let(:school_owner) {school.owner}

  before(:each) do
    User.where('school_id is not null').update_all(school_id: nil)
    Teacher.delete_all
    SchoolInvitation.delete_all
    School.delete_all
    UserMailer.deliveries.clear
    emulate_client
  end

  describe "account school" do
    it "allows invitation" do

      sign_in_poltergeist school_owner
      visit "/client#/account"

      find('#account-school-link').trigger(:click)

      find('h4', text: 'Management Preference')

      find('.profile-nav a', text: 'members' ).trigger(:click)

      find('a.invite-dialog', text: 'INVITE TEACHER').trigger(:click)

      find('h1', text: 'invite teacher')
      fill_in "first_name", with: "Seth"
      fill_in "last_name", with: "Call"
      fill_in "email", with: "seth+invited_teacher@jamkazam.com"
      find('#invite-school-user-dialog .actions a', text: 'SEND INVITATION').trigger(:click)

      find('#banner .dialog-inner', text: 'Your invitation has been sent!')
      SchoolInvitation.count.should eql 1
      school_invitation = SchoolInvitation.first
      school_invitation.email.should eql "seth+invited_teacher@jamkazam.com"

      find('.teacher-invites td.description', "#{school_invitation.first_name} #{school_invitation.last_name}")

      UserMailer.deliveries.count.should eql 1

      # let's try to resend it.
      find('a.resend', text:'resend invitation').trigger(:click)
      find('h2', text: 'invitation resent') # wait for notification to show
      UserMailer.deliveries.count.should eql 2

      find('a.delete', text: 'delete').trigger(:click)

      find('.teacher-invites p', text: 'No pending invitations')

      # make an invitation, and accept it, and check if users list after a refresh


    end
  end
end
