require 'spec_helper'

describe "Book Single Recurring Lesson", :js => true, :type => :feature, :capybara_feature => true do

  subject { page }

  let(:user) { FactoryGirl.create(:user, traditional_band: true,paid_sessions: true, paid_sessions_hourly_rate: 1,  paid_sessions_daily_rate:1 ) }
  let(:teacher_user) {FactoryGirl.create(:teacher_user, first_name: "Teacher1", ready_for_session_at: Time.now)}
  let(:teacher_user2) {FactoryGirl.create(:teacher_user, ready_for_session_at: Time.now)}
  let(:teacher_user3) {FactoryGirl.create(:teacher_user, ready_for_session_at: Time.now)}

  after(:each) do
    Timecop.return
  end


  before(:each) do


    LessonBooking.destroy_all
    Recording.delete_all
    Diagnostic.delete_all
    User.delete_all

    UserMailer.deliveries.clear
    emulate_client
    # create an old test drive and fakely use up all the credits so that we can book the lesson
    Timecop.travel(Date.new(2016, 03, 01))
    testdrive_lesson(user, teacher_user3)
    user.remaining_test_drives = 0
    user.save!
    user.reload

    teacher_user.teacher.ready_for_session_at = Time.now
    teacher_user.teacher.save!
    teacher_user.teacher.price_per_lesson_60_cents.should eql 3000
    Teacher.index(user, {})[:query].count.should eql 1

    teacher_user.teacher.ready_for_session_at = Time.now
    teacher_user.teacher.save!
    teacher_user.password.should eql 'foobar'
    teacher_user.teacher.price_per_lesson_60_cents.should eql 3000

    Teacher.index(user, {})[:query].count.should eql 1
  end

  describe "register via showing interesting in teacher 1st" do

    it "succeeds" do


      Timecop.travel(Date.new(2016, 04, 01))

      sign_in_poltergeist user

      visit "/client#/teachers/search"

      find('.teacher-search-result[data-teacher-id="' + teacher_user.id + '"] .try-normal').trigger(:click)


      # switch to recurring
      find(".lesson-frequency-recurring ins", visible: false).trigger(:click)

      # book the lesson
      select "Monday", from: "day-of-week-1"

      select "Tuesday", from: "day-of-week-2"

      fill_in 'user-description', with: 'abc def dog neck'

      select('60 Minute Lesson Each Week - $30.00 Per Week', :from => "booking-options-for-teacher")
      sleep 3

      find('a.book-lesson-btn', text: 'BOOK LESSON').trigger(:click)

     # find('h2', text: 'enter payment info for lesson')


      #fill_in 'card-number', with: '4111111111111111'
      #fill_in 'expiration', with: '11/2016'
      #fill_in 'cvv', with: '111'
      #fill_in 'zip', with: '78759'

      #find('.purchase-btn').trigger(:click)

      # we tell user they have test drive purchased, and take them to the teacher screen
      find('#banner h1', text: 'Lesson Requested')
      # dismiss banner
      find('a.button-orange', text:'CLOSE').trigger(:click)


      user.student_lesson_bookings.count.should eql 2
      lesson_booking = user.student_lesson_bookings.order(:created_at).last
      lesson_booking.is_requested?.should be true
      lesson_booking.card_presumed_ok.should be true
      lesson_booking.recurring.should be true
      lesson_booking.is_monthly_payment?.should be false

      lesson_booking = LessonBooking.where(teacher_id: teacher_user).first
      lesson_booking.should_not be_nil
      lesson_session = LessonSession.where(teacher_id: teacher_user).first
      lesson_session.teacher.should eql teacher_user

      lesson_package_purchase = LessonPackagePurchase.where(user_id: user.id, teacher_id: teacher_user.id).first
      lesson_package_purchase.should be_nil
      user.reload
      user.remaining_test_drives.should eql 0
      user.sales.count.should eql 0

      # jamclass scren
      find('h2', text: 'my lessons')
      find('tr[data-lesson-session-id="' + lesson_session.id + '"] .displayStatusColumn', text: 'Requested')
      find('tr[data-lesson-session-id="' + lesson_session.id + '"] .first_name', text: teacher_user.first_name)

      # open up hover
      find('tr[data-lesson-session-id="' + lesson_session.id + '"] .lesson-session-actions-btn').trigger(:click)

      # check out the status
      find('li[data-lesson-option="status"] a', text: 'View Status').trigger(:click)

      # and now go to the session status screen
      find('h2', text: 'your lesson has been requested')

      # let's make a second request to a different teacher now

      # let's make sure we can ask for another lesson too!
      teacher_user2.teacher.ready_for_session_at = Time.now
      teacher_user2.teacher.save!

      visit "/client#/teachers/search"
      find('a.teacher-search-options').trigger(:click)
      find('a.search-btn').trigger(:click)

      find('.teacher-search-result[data-teacher-id="' + teacher_user2.id + '"] .try-normal').trigger(:click)

      # switch back to single
      find(".lesson-frequency-single ins", visible: false).trigger(:click)

      # book the lesson
      fill_in "slot-1-date", with: "Sun Apr 17 2016"
      #find('.slot.slot-1 input.hasDatepicker').trigger(:click)
      # click 4-6
      find('td a', text: '17').trigger(:click)

      #find('.slot.slot-2 input.hasDatepicker').trigger(:click)
      # click 4-7
      fill_in "slot-2-date", with: "Mon Apr 18 2016"
      find('td a', text: '18').trigger(:click)

      fill_in 'user-description', with: 'abc def dog neck'

      select('60 Minute Lesson for $30.00', :from => "booking-options-for-teacher")
      sleep 3

      find('a.book-lesson-btn', text: 'BOOK LESSON').trigger(:click)

      # we tell user they have test drive purchased, and take them to the teacher screen
      find('#banner h1', text: 'Lesson Requested')
      # dismiss banner
      find('a.button-orange', text:'CLOSE').trigger(:click)


      lesson_booking = LessonBooking.where(teacher_id: teacher_user2).first
      lesson_booking.should_not be_nil
      lesson_booking.recurring.should be false
      LessonSession.where(teacher_id: teacher_user2).count.should eql 1

      lesson_package_purchase = LessonPackagePurchase.where(user_id: user.id, teacher_id: teacher_user.id).first
      lesson_package_purchase.should be_nil
      user.reload
      user.remaining_test_drives.should eql 0
      user.sales.count.should eql 0


      # approve by teacher:
      lesson_session1 = LessonSession.where(teacher_id: teacher_user).first
      teacher_approve(lesson_session1)

      lesson_booking1 = LessonBooking.where(teacher_id: teacher_user).first
      lesson_booking1.lesson_sessions.count.should eql 2
      lesson_session2 = LessonSession.where(teacher_id: teacher_user).last

      successful_lesson(lesson_session1)

      LessonSession.hourly_check
      lesson_session1.reload
      lesson_session1.analysed.should be true
      analysis = JSON.parse(lesson_session1.analysis)
      analysis["reason"].should eql LessonSessionAnalyser::SUCCESS
      lesson_session1.billing_attempts.should be true
      lesson_session1.billed.should eql true
      lesson_session1.success.should be true
      lesson_session1.lesson_payment_charge.billed.should be true
      lesson_session1.lesson_payment_charge.amount_in_cents.should eql (3000 + (3000 * 0.0825).round)
      lesson_session1.lesson_payment_charge.fee_in_cents.should eql 0
      lesson_session1.lesson_payment_charge.stripe_charge_id.should_not be_nil
      lesson_session1.lesson_payment_charge.post_processed.should be true
      lesson_session1.lesson_payment_charge.sent_billing_notices.should be true
      lesson_session1.lesson_payment_charge.billing_attempts.should eql 1

      LessonBooking.hourly_check

      lesson_session1.reload
      teacher_distribution = lesson_session1.teacher_distribution
      teacher_distribution.amount_in_cents.should eql 3000
      teacher_distribution.ready.should be true
      teacher_distribution.distributed.should be false

      # check the second session, which hasn't come due yet because it's 1 week ahead of the other session
      lesson_session2.reload
      lesson_session2.analysed.should be true
      analysis = JSON.parse(lesson_session2.analysis)
      analysis["reason"].should eql LessonSessionAnalyser::SESSION_ONGOING
      lesson_session2.billing_attempts.should eql 0
      lesson_session2.billed.should eql false
      lesson_session2.success.should be false
      lesson_session2.teacher_distribution.should be_nil

      failed_lesson(lesson_session2)

      LessonSession.hourly_check
      LessonBooking.hourly_check

      # check the 2nd session again, which should now have
      lesson_session2.reload
      lesson_session2.analysed.should be true
      analysis = JSON.parse(lesson_session2.analysis)
      analysis["reason"].should eql LessonSessionAnalyser::SESSION_ONGOING
      lesson_session2.billing_attempts.should eql 0
      lesson_session2.billed.should eql false
      lesson_session2.success.should be false
      lesson_session2.teacher_distribution.should be_nil
    end
  end
end
